本节目的:创建一个简单的Spring -boot 实例,并简单使用 thymeleaf 模板
1. 环境搭建:环境使用spring-boot,主要依赖如下
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<!-- spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
2.创建主要工程,主要文件有main函数、controller(包含构建返回结果数据)、简单的Html展示页面(thymeleaf)
main函数:
@SpringBootApplication
public class MianApplication {
public static void main( String[] args )
{
SpringApplication.run(DemoController.class, args);
}
}
Controller 层函数:
@EnableAutoConfiguration
@RequestMapping("/demo")
@Controller
public class DemoController {
@RequestMapping("/thymeleaf")
@ResponseBody
public ModelAndView thymeleaf(ModelAndView model) {
model.addObject("name", "zhangsan");
model.setViewName("hello11");
return model;
}
}
资源配置:在src/main/source中添加文件aplication.properties:
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
在上面我们看到前缀文件名称为:templates,路径是当前目录下,因此在当前目录src/main/resource下创阿金templates文件
夹,然后添加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}"></p>
</body>
</htm
大功告成,。然后我们运行一下 :
启动服务:
然后使用浏览器访问:http://localhost:8080/demo/thymeleaf :