SpringMVC整合Thymeleaf3

(1).pom添加相关依赖

 

1     <dependency>
2       <groupId>org.thymeleaf</groupId>
3       <artifactId>thymeleaf-spring4</artifactId>
4       <version>3.0.11.RELEASE</version>
5     </dependency>

(2).配置三个启用Thymeleaf与Spring集成的bean

 1 @Configuration
 2 @EnableWebMvc   //启用Spring MVC 注解驱动  <mvc:annotation-driven />
 3 @ComponentScan("cn.coreqi.controller")
 4 public class WebConfig extends WebMvcConfigurerAdapter {
 5 
 6     //配置Thymeleaf视图解析器
 7     @Bean
 8     public ViewResolver viewResolver(TemplateEngine templateEngine){
 9         ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
10         viewResolver.setTemplateEngine(templateEngine);
11         viewResolver.setCharacterEncoding("utf-8");
12         return viewResolver;
13     }
14 
15     //创建模板引擎
16     @Bean
17     public TemplateEngine templateEngine(ITemplateResolver templateResolver){
18         SpringTemplateEngine templateEngine = new SpringTemplateEngine();
19         templateEngine.setTemplateResolver(templateResolver);
20         return templateEngine;
21     }
22 
23     //创建Thymeleaf模板解析器
24     @Bean
25     public ITemplateResolver templateResolver(){
26         SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
27         resolver.setPrefix("/WEB-INF/templates/");
28         resolver.setSuffix(".html");
29         resolver.setTemplateMode(TemplateMode.HTML);
30         resolver.setCacheable(false);
31         resolver.setCharacterEncoding("utf-8");
32         return resolver;
33     }

(3)编写测试控制器

 1 @Controller
 2 @RequestMapping({"/","/homepage"})
 3 public class HomeController {
 4 
 5     @GetMapping()
 6     public String home(Map<String,Object> map){
 7         map.put("ceshi","Thymeleaf模板引擎已启动");
 8         return "home";
 9     }
10 }

(4)编写页面

 1 <!DOCTYPE html>
 2 <html lang="en" xmlns:th="http://www.thymeleaf.org">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>templates</title>
 6 </head>
 7 <body>
 8     <h1 th:text="${ceshi}"></h1>
 9 </body>
10 </html>

 

posted @ 2019-01-12 14:47  SpringCore  阅读(774)  评论(0编辑  收藏  举报