【Java Web开发学习】Spring4整合thymeleaf视图解析
【Java Web开发学习】Spring4整合thymeleaf视图解析
目录
转载:https://www.cnblogs.com/yangchongxing/p/9111008.html
Thymeleaf官网:https://www.thymeleaf.org
Thymeleaf模板是原生的,不依赖于标签库。它能在接受原始HTML的地方进行编辑和渲染。因为它没有与Servlet规范耦合,因此Thymeleaf模板能够进入JSP所无法涉足的领域。
Eclipse插件:http://www.thymeleaf.org/eclipse-plugin-update-site/
依赖的jar包
thymeleaf-3.0.9.RELEASE.jar
thymeleaf-spring4-3.0.9.RELEASE.jar
unbescape-1.1.6.RELEASE.jar
attoparser-2.0.5.RELEASE.jar
slf4j-api-1.7.25.jar
slf4j-log4j12-1.7.25.jar
Spring中使用Thymeleaf,我们需要配置三个启用Thymeleaf与Spring集成的bean:
ThymeleafViewResolver:将逻辑视图名称解析为Thymeleaf模板视图;
SpringTemplateEngine:处理模板并渲染结果;
SpringResourceTemplateResolver:加载Thymeleaf模板。
@Bean public SpringResourceTemplateResolver templateResolver() { SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setPrefix("/"); templateResolver.setSuffix(".html"); templateResolver.setCharacterEncoding("UTF-8"); templateResolver.setTemplateMode("HTML5"); return templateResolver; } @Bean public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver); return templateEngine; } @Bean public ViewResolver viewResolver(SpringTemplateEngine templateEngine) { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setContentType("text/html; charset=utf-8");
viewResolver.setCharacterEncoding("UTF-8"); viewResolver.setTemplateEngine(templateEngine); return viewResolver; }
模板
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <span th:text="${name}"></span> </body> </html>
控制器
package cn.ycx.bms.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class IndexController { @RequestMapping("/") public ModelAndView index(Model model) { ModelAndView mav = new ModelAndView(); mav.addObject("name", "你好"); mav.setViewName("index"); return mav; } }