springBoot使用thymeleaf和freemarker模板引擎
1.添加thymeleaf或者freemarker的依赖包
<!-- 添加thymeleaf的依赖. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
<!-- freemarker的依赖配置信息 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
2.在application.properties文件中添加thymeleaf或freemarker配置并关闭缓存
######################################################## ###THYMELEAF (ThymeleafAutoConfiguration) ######################################################## #spring.thymeleaf.prefix=classpath:/templates/ #spring.thymeleaf.suffix=.html #spring.thymeleaf.mode=HTML5 #spring.thymeleaf.encoding=UTF-8 # ;charset=<encoding> is added #spring.thymeleaf.content-type=text/html # set to false for hot refresh #\u5f00\u53d1\u8fc7\u7a0b\u5efa\u8bae\u5173\u95ed\u7f13\u5b58. spring.thymeleaf.cache=false
########################################################
###FREEMARKER (FreeMarkerAutoConfiguration)
########################################################
spring.freemarker.allow-request-override=false
spring.freemarker.cache=false
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
spring.freemarker.suffix=.ftl
#spring.freemarker.template-loader-path=classpath:/templates/ #comma-separated list
#spring.freemarker.view-names= # whitelist of view names that can be resolved
3.在src/main/resources下新建templates文件夹,存放thymeleaf(xx.html)或freemarker(xx.ftl)模板
hello.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Insert title here</title> </head> <body> <h1> Hello,thymeleaf <br /> This is my first thymeleaf demo. <hr /> welcome <span th:text="${name}"></span> </h1> </body> </html>
helloFtl.ftl
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>Insert title here</title> </head> <body> hello ${name} </body> </html>
4.编写controller类(注意,使用@Controller注解,而不是@RestController注解)
Controller @RequestMapping("/templates") public class TemplatesController { /** * 映射地址是:/templates/hello * @return */ @RequestMapping("/hello") public String hello(Map<String,Object> map){ //返回的是ModelAndView对象; // ModelAndView mv = new ModelAndView("hello"); // return mv; map.put("name","Andy"); return "hello"; } @RequestMapping("/helloFtl") public String helloFtl(Map<String,Object> map){ map.put("name","Andy"); return "helloFtl"; } }
5.编写启动类(App.Java)