zoukankan      html  css  js  c++  java
  • SPRING IN ACTION 第4版笔记-第六章RENDERING WEB VIEWS-006- 使用thymeleaf(TemplateResolver、SpringTemplateEngine、ThymeleafViewResolver、th:include、th:object、th:field="*{firstName}")

    一、在Spring中使用thymeleaf的步骤

    1.配置

    In order to use Thymeleaf with Spring, you’ll need to configure three beans that enable Thymeleaf-Spring integration:
     A ThymeleafViewResolver that resolves Thymeleaf template views from logical view names
     A SpringTemplateEngine to process the templates and render the results
     A TemplateResolver that loads Thymeleaf templates

    ThymeleafViewResolver is an implementation of Spring MVC ’s ViewResolver . Just like any view resolver, it takes a logical view name and resolves a view. But in this case,that view is ultimately a Thymeleaf template.

    Notice that the ThymeleafViewResolver bean is injected with a reference to theSpringTemplateEngine bean. SpringTemplateEngine is a Spring-enabled Thymeleaf engine for parsing templates and rendering results based on those templates. As you can see, it’s injected with a reference to the TemplateResolver bean.

    TemplateResolver is what ultimately locates the templates. It’s configured much as you previously configured InternalResourceViewResolver with prefix and suffix properties. The prefix and suffix are applied to the logical view name to locate the Thymeleaf template. Its templateMode property is also set to HTML5 , indicating that the templates resolved are expected to render HTML5 output.

    (1)Java配置

     1 package spittr.web;
     2 
     3 import org.springframework.context.annotation.Bean;
     4 import org.springframework.context.annotation.ComponentScan;
     5 import org.springframework.context.annotation.Configuration;
     6 import org.springframework.web.servlet.ViewResolver;
     7 import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
     8 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
     9 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    10 import org.thymeleaf.spring4.SpringTemplateEngine;
    11 import org.thymeleaf.spring4.view.ThymeleafViewResolver;
    12 import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
    13 import org.thymeleaf.templateresolver.TemplateResolver;
    14 
    15 @Configuration
    16 @EnableWebMvc
    17 @ComponentScan("spittr.web")
    18 public class WebConfig extends WebMvcConfigurerAdapter {
    19 
    20   @Bean
    21   public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
    22     ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
    23     viewResolver.setTemplateEngine(templateEngine);
    24     return viewResolver;
    25   }
    26   @Bean
    27   public SpringTemplateEngine templateEngine(TemplateResolver templateResolver) {
    28     SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    29     templateEngine.setTemplateResolver(templateResolver);
    30     return templateEngine;
    31   }
    32 
    33   @Bean
    34   public TemplateResolver templateResolver() {
    35     TemplateResolver templateResolver = new ServletContextTemplateResolver();
    36     templateResolver.setPrefix("/WEB-INF/views/");
    37     templateResolver.setSuffix(".html");
    38     //indicating that the templates resolved are expected to render  HTML5 output
    39     templateResolver.setTemplateMode("HTML5");
    40     
    41     return templateResolver;
    42   }
    43     
    44   @Override
    45   public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    46     configurer.enable();
    47   }
    48   
    49 }

    (2)Xml配置

     1 <bean id="viewResolver"
     2 class="org.thymeleaf.spring3.view.ThymeleafViewResolver"
     3 p:templateEngine-ref="templateEngine" />
     4 <bean id="templateEngine"
     5 class="org.thymeleaf.spring3.SpringTemplateEngine"
     6 p:templateResolver-ref="templateResolver" />
     7 <bean id="templateResolver" class=
     8 "org.thymeleaf.templateresolver.ServletContextTemplateResolver"
     9 p:prefix="/WEB-INF/templates/"
    10 p:suffix=".html"
    11 p:templateMode="HTML5" />

    2.定义Thymeleaf模板

    (1)标签介绍

     1 <a th:href="@{/spitter/register}">Register</a>
     2 
     3 <div th:fragment="header">
     4 
     5 <img th:src="@{/resources/images/spitter_logo_50.png}" border="0" /></a>
     6 
     7 <div id="header" th:include="page :: header"></div>
     8 <form method="POST" th:object="${spitter}">
     9 
    10 <div class="errors" th:if="${#fields.hasErrors('*')}">
    11           <ul>
    12             <li th:each="err : ${#fields.errors('*')}" 
    13                 th:text="${err}">Input is incorrect</li>
    14           </ul>
    15         </div>
    16 
    17 <label th:class="${#fields.hasErrors('firstName')}? 'error'">First Name</label>: 
    18           <input type="text" th:field="*{firstName}"  
    19                  th:class="${#fields.hasErrors('firstName')}? 'error'" /><br/>
    20 
    21 <span th:text="${spitter.username}">username</span><br/>
    22 
    23 <li th:each="spittle : ${spittleList}" 
    24               th:id="'spittle_' + ${spittle.id}">
    25             <div class="spittleMessage" th:text="${spittle.message}">Spittle message</div>
    26             <div>
    27               <span class="spittleTime" th:text="${spittle.time}">spittle timestamp</span>
    28               <span class="spittleLocation" th:text="'{' + ${spittle.latitude} + ', ' + ${spittle.longitude} + ')'">lat, long</span>
    29             </div>
    30           </li>

    thymeleaf标签的优势是定在原生的html里,不会破坏原来的html结构,可以用浏览器直接打开,只是动态计算的东西无效。

    (2)home.html

     1 <html xmlns="http://www.w3.org/1999/xhtml"
     2       xmlns:th="http://www.thymeleaf.org">
     3   <head>
     4     <title>Spitter</title>
     5     <link rel="stylesheet" 
     6           type="text/css" 
     7           th:href="@{/resources/style.css}"></link>
     8   </head>
     9   <body>
    10     <div id="header" th:include="page :: header"></div>
    11   
    12     <div id="content">
    13       <h1>Welcome to Spitter</h1>
    14   
    15       <a th:href="@{/spittles}">Spittles</a> | 
    16       <a th:href="@{/spitter/register}">Register</a>
    17       
    18       <br/>
    19       
    20       View: <span th:text="${view}">unknown</span>
    21     </div>
    22     <div id="footer" th:include="page :: copy"></div>
    23   </body>
    24 </html>

    (2.1)registerForm.html

     1 <html xmlns="http://www.w3.org/1999/xhtml"
     2       xmlns:th="http://www.thymeleaf.org">
     3   <head>
     4     <title>Spitter</title>
     5     <link rel="stylesheet" type="text/css" 
     6           th:href="@{/resources/style.css}"></link>
     7   </head>
     8   <body>
     9     <div id="header" th:include="page :: header"></div>
    10 
    11     <div id="content">
    12       <h1>Register</h1>
    13   
    14       <form method="POST" th:object="${spitter}">
    15         <div class="errors" th:if="${#fields.hasErrors('*')}">
    16           <ul>
    17             <li th:each="err : ${#fields.errors('*')}" 
    18                 th:text="${err}">Input is incorrect</li>
    19           </ul>
    20         </div>
    21         <label th:class="${#fields.hasErrors('firstName')}? 'error'">First Name</label>: 
    22           <input type="text" th:field="*{firstName}"  
    23                  th:class="${#fields.hasErrors('firstName')}? 'error'" /><br/>
    24   
    25         <label th:class="${#fields.hasErrors('lastName')}? 'error'">Last Name</label>: 
    26           <input type="text" th:field="*{lastName}"
    27                  th:class="${#fields.hasErrors('lastName')}? 'error'" /><br/>
    28   
    29         <label th:class="${#fields.hasErrors('email')}? 'error'">Email</label>: 
    30           <input type="text" th:field="*{email}"
    31                  th:class="${#fields.hasErrors('email')}? 'error'" /><br/>
    32   
    33         <label th:class="${#fields.hasErrors('username')}? 'error'">Username</label>: 
    34           <input type="text" th:field="*{username}"
    35                  th:class="${#fields.hasErrors('username')}? 'error'" /><br/>
    36   
    37         <label th:class="${#fields.hasErrors('password')}? 'error'">Password</label>: 
    38           <input type="password" th:field="*{password}"  
    39                  th:class="${#fields.hasErrors('password')}? 'error'" /><br/>
    40         <input type="submit" value="Register" />
    41       
    42       
    43       </form>
    44     </div>
    45     <div id="footer" th:include="page :: copy"></div>
    46   </body>
    47 </html>

    解析:

    a)由<form th:object="${spitter}">指定了对象,By using th:field="*{firstName}", you get both a value attribute set to the value of firstName and also a name attribute set to firstName .


    b)<li th:each>:

    The th:each attribute on the <li> tag instructs Thymeleaf to render the <li> one time for each error,assigning the current error in each iteration to a variable named err .
    The <li> tag also has a th:text attribute. This attribute instructs Thymeleaf to evaluate an expression (in this case, the value of the err variable) and render its value as the body of the <li> tag. In effect, there will be one <li> for each error, displaying
    the text of that error.

    c)You may be wondering about the difference between the expressions wrapped with ${} and those wrapped with *{} . The ${} expressions (such as ${spitter} ) are variable expressions. Normally, these are Object-Graph Navigation Language ( OGNL )expressions (http://commons.apache.org/proper/commons-ognl/). But when used with Spring, they’re SpEL expressions. In the case of ${spitter} , it resolves to the model property whose key is spitter .

    As for *{} expressions, they’re selection expressions. Whereas variable expressions are evaluated against the entire SpEL context, selection expressions are evaluated on a selected object. In the case of the form, the selected object is the one given in the

    (3)page.html

     1 <html xmlns="http://www.w3.org/1999/xhtml"
     2       xmlns:th="http://www.thymeleaf.org">
     3       
     4   <body>
     5   
     6     <div th:fragment="header">
     7       <a th:href="@{/}">
     8         <img th:src="@{/resources/images/spitter_logo_50.png}" border="0" /></a>
     9     </div>
    10 
    11     <div>Content goes here</div>
    12   
    13     <div th:fragment="copy">Copyright &copy; Craig Walls</div>
    14   </body>
    15   
    16 </html>

    (4)spittles.html

     1 <html xmlns="http://www.w3.org/1999/xhtml"
     2       xmlns:th="http://www.thymeleaf.org">
     3   <head>
     4     <title>Spitter</title>
     5     <link rel="stylesheet" 
     6           type="text/css" 
     7           th:href="@{/resources/style.css}" ></link>
     8   </head>
     9   <body>
    10     <div id="header" th:include="page :: header"></div>
    11   
    12     <div id="content">
    13       <div class="spittleForm">
    14         <h1>Spit it out...</h1>
    15         <form method="POST" name="spittleForm">
    16           <input type="hidden" name="latitude" />
    17           <input type="hidden" name="longitude" />
    18           <textarea name="message" cols="80" rows="5"></textarea><br/>
    19           <input type="submit" value="Add" />
    20         </form>
    21       </div>
    22       <div class="listTitle">
    23         <h1>Recent Spittles</h1>
    24         <ul class="spittleList">
    25           <li th:each="spittle : ${spittleList}" 
    26               th:id="'spittle_' + ${spittle.id}">
    27             <div class="spittleMessage" th:text="${spittle.message}">Spittle message</div>
    28             <div>
    29               <span class="spittleTime" th:text="${spittle.time}">spittle timestamp</span>
    30               <span class="spittleLocation" th:text="'{' + ${spittle.latitude} + ', ' + ${spittle.longitude} + ')'">lat, long</span>
    31             </div>
    32           </li>
    33         </ul>
    34       </div>
    35     </div>
    36     
    37     <div id="footer" th:include="page :: copy"></div>
    38   </body>
    39 </html>

    (5)spittle.html

     1 <html xmlns="http://www.w3.org/1999/xhtml"
     2       xmlns:th="http://www.thymeleaf.org">
     3   <head>
     4     <title>Spitter</title>
     5     <link rel="stylesheet" 
     6           type="text/css" 
     7           th:href="@{/resources/style.css}"></link>
     8   </head>
     9   <body>
    10     <div id="header" th:include="page :: header"></div>
    11   
    12     <div id="content">
    13       <div class="spittleView">
    14         <div class="spittleMessage" th:text="#{spittle.message}">Spittle message</div>
    15         <div>
    16           <span class="spittleTime" th:text="#{spittle.time}">spittle timestamp</span>
    17         </div>
    18       </div>
    19     </div>
    20     <div id="footer" th:include="page :: copy"></div>
    21     
    22   </body>
    23 </html>

    (6)profile.html

     1 <html xmlns="http://www.w3.org/1999/xhtml"
     2       xmlns:th="http://www.thymeleaf.org">
     3   <head>
     4     <title>Spitter</title>
     5     <link rel="stylesheet" 
     6           type="text/css" 
     7           th:href="@{/resources/style.css}"></link>
     8   </head>
     9   <body>
    10     <div id="header" th:include="page :: header"></div>
    11 
    12     <div id="content">
    13       <h1>Your Profile</h1>
    14       <span th:text="${spitter.username}">username</span><br/>
    15       <span th:text="${spitter.firstName}">First</span> <span th:text="${spitter.lastName}">Last</span><br/>
    16       <span th:text="${spitter.email}">email</span>
    17     </div>
    18 
    19     <div id="footer" th:include="page :: copy"></div>
    20   </body>
    21 </html>

    二、SpringMVC view层的总结

    Thymeleaf is a compelling option because it enables the creation of natural templates that are still pure HTML and can be edited and viewed in the raw as if they were static HTML , but still render dynamic model data at runtime. Moreover, Thymeleaf templates are largely decoupled from servlets, enabling them to be used in places where JSP s can’t.

  • 相关阅读:
    第十四章:(2)Spring Boot 与 分布式 之 Dubbo + Zookeeper
    第十四章:(1)Spring Boot 与 分布式 之 分布式介绍
    第九章:Redis 的Java客户端Jedis
    第十三章:(2)Spring Boot 与 安全 之 SpringBoot + SpringSecurity + Thymeleaf
    第八章:(1)Redis 的复制(Master/Slave)
    java学习
    周末总结4
    java
    Cheatsheet: 2012 12.17 ~ 12.31
    Cheatsheet: 2012 10.01 ~ 10.07
  • 原文地址:https://www.cnblogs.com/shamgod/p/5244560.html
Copyright © 2011-2022 走看看