一、理解解析
Spring MVC定义了一个名为ViewResolver的接口,它大致如下所示:
public interface ViewResolver { View resolverViewName(String viewName, Locale locale) throws Exception; }
View是另外一个接口。
public interface View { String getContentType(); void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception; }
View接口的任务就是接受模型以及Servlet的request和response对象,并将输出结果渲染到response中。
我们需要做的就是编写ViewResolver和View的实现,将要渲染的内容放到response中,进而展现到用户的浏览器中。实际上,Spring提供了多个内置的实现。
二、使用Thymeleaf
1. 配置Thymeleaf视图解析器
为了要在Spring中使用Thymeleaf,我们需要配置三个启用Thymeleaf与Spring集成的bean:
- ThymeleafViewResolver:将逻辑视图名称解析为Thymeleaf模板视图;
- SpringTemplateEngine:处理模板并渲染结果;
- TemplateResolver:加载Thymeleaf模板。
如下为声明这些bean的Java配置。
Thymeleaf3 之前的版本:
@Bean public ViewResolver viewResolver(SpringTemplateEngine templateEngine) { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine); return viewResolver; } @Bean public TemplateEngine templateEngine(TemplateResolver templateResolver) { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver); return templateEngine; } @Bean public TemplateResolver templateResolver() { TemplateResolver templateResolver = new ServletContextTemplateResolver(); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); return templateResolver; }
thymeleaf3 版本:
@Bean public ViewResolver viewResolver(SpringTemplateEngine templateEngine) { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine); return viewResolver; } @Bean public TemplateEngine templateEngine(TemplateResolver templateResolver) { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver); return templateEngine; } @Bean public ITemplateResolver templateResolver() { TemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); return templateResolver; }
如果你更愿意使用XML来配置bean,那么如下的<bean>声明能够完成该任务。
<bean id="viewResolver" class="org.thymeleaf.spring3.view.ThymeleafViewResolver" p:templateEngine-ref="templateEngine" /> <bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine" p:templateResolver-ref="templateResolver" /> <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver" p:prefix="/WEB-INF/templates" p:suffix=".html" p:templateMode="HTML5" />
2. 定义Thymeleaf模板
Thymeleaf在很大程度上就是HTML文件,与JSP不同,它没有什么特殊的标签或标签库。Thymeleaf之所以能够发挥作用,是因为它通过自定义的命名控件,为标准的HTML标签集合添加Thymeleaf属性。