[筆記]《Spring實戰》- 渲染Web視圖
阿新 • • 發佈:2018-05-02
spring gin get 模板 gte ffi urn 發揮 content
一、理解解析
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) throwsException; }
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屬性。
[筆記]《Spring實戰》- 渲染Web視圖