零基础myeclipse下springBoot+maven+thymeleaf的开发(2)
接下
现在我们开始代码的编写,首先先写application.java这个,这里写的是一些相当于spring配置文件xml那样的东西如bean。我们先然昨天搭建的环境跑起来,代码如下:
@EnableAutoConfiguration
@SpringBootApplication
@ComponentScan
public class Application {
private static Logger logger = Logger.getLogger(Application.class);
/**
* Start
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
logger.info("SpringBoot Start Success");
}
}
然后我们run起来,然后去浏览器打开:localhost:8080,如图所示:
好了这样我们基本就以及把springboot的开发环境搭好了。
可能有些人会出现报错找不到templates,那么就在src/main/resources下创建一个templates,下面这个文件我们会用到,因为我搭建的是thymeleaf,它默认会去加载这个文件。我们的html也就都放这里,还有一点需要注意,由于springboot不建议使用jsp,如果你建的是jsp访问的时候解析不了,出现整个源代码都打印了 出来。如果想用jsp需要修改一些配置文件。所以我们选用了模板引擎thymeleaf来代替jsp
下面写一个hellocontrol
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(@RequestParam(value="name", required=false, defaultValue="World!!") String name, Model model) {
model.addAttribute("name", name);
return "hello";
}
}
然后在templates下创建hello.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>hello</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="'Hello!, ' + ${name} + '!'" >3333</p>
</body>
</html>
好了这样重启一下就可以了
默认不传值得情况打印出hello world!,如果我们输入:http://localhost:8080/hello?name=cwh
则打印出:hello,cwh!
有没有发现如果你修改了html文件发现访问时并没有改变,这就是thymeleaf缓存的作用,我们修改下把缓存关闭就好了,在src/main/resources下新建一个application.properties,然后添加
spring.thymeleaf.cache=false
这样重启之后就可以了。
还有个比较烦的事就是,每次修改java文件总是要去重启多麻烦呀,不用急,采用热部署搞定。下来我们在pom.xml加入这个依赖:
<!-- 热部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
然后update project,接着run configuration,修改下
把你的刚刚下载的jar包加进去,
如图所示:
OK,这样再重启就搞定热部署了。
未完待续。。。。

浙公网安备 33010602011771号