Integrating Thymeleaf with Spring
Posted zhenhong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Integrating Thymeleaf with Spring相关的知识,希望对你有一定的参考价值。
这个是基于注解的配置方式,基于配置文件的http://www.cnblogs.com/honger/p/6875148.html
一、整体结构图
二、web.xml文件,这里使用了注解的方式
<?xml version="1.0" encoding="utf-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1" metadata-complete="true"> <!-- Configure ContextLoaderListener to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext --> <context-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </context-param> <!-- Configuration locations must consist of one or more comma- or space-delimited fully-qualified @Configuration classes. Fully-qualified packages may also be specified for component-scanning --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>com.test.dao.configure.ApplicationConfigure</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext instead of the default XmlWebApplicationContext --> <init-param> <param-name>contextClass</param-name> <param-value> org.springframework.web.context.support.AnnotationConfigWebApplicationContext </param-value> </init-param> <!-- Again, config locations must consist of one or more comma-(逗号) or space-delimited(空格) and fully-qualified @Configuration classes --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>com.test.mvc.configure.SpringWebConfig</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
三、SpringMVC注解配置文件
package com.test.mvc.configure; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.thymeleaf.spring4.SpringTemplateEngine; import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver; import org.thymeleaf.spring4.view.ThymeleafViewResolver; import org.thymeleaf.templatemode.TemplateMode; import com.test.fomatter.MyDateFormatter; @Configuration @EnableWebMvc//<mvc:annotation-driven/> @ComponentScan(basePackages = { "com.test.controller" }, includeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = { org.springframework.stereotype.Controller.class }) }) public class SpringWebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware { private ApplicationContext applicationContext; public SpringWebConfig() { super(); } public void setApplicationContext(final ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } /* ******************************************************************* */ /* GENERAL CONFIGURATION ARTIFACTS */ /* Static Resources, i18n Messages, Formatters (Conversion Service) */ /* 配置静态资源,i18n 信息, 格式转换器 */ /* ******************************************************************* */ @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { super.addResourceHandlers(registry); registry.addResourceHandler("/images/**").addResourceLocations("/WEB-INF/images/"); registry.addResourceHandler("/css/**").addResourceLocations("/WEB-INF/css/"); registry.addResourceHandler("/js/**").addResourceLocations("/WEB-INF/js/"); } @Bean public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); // 设置国际化资源的baseName messageSource.setBasename("messages"); return messageSource; } /** * 添加转换器 */ @Override public void addFormatters(final FormatterRegistry registry) { super.addFormatters(registry); registry.addFormatter(varietyFormatter()); } @Bean public MyDateFormatter varietyFormatter() { return new MyDateFormatter("yyyy-MM-dd"); } /* **************************************************************** */ /* THYMELEAF-SPECIFIC ARTIFACTS */ /* TemplateResolver <- TemplateEngine <- ViewResolver */ /* **************************************************************** */ /** * thymeleaf的模板解析器 * * @return */ @Bean public SpringResourceTemplateResolver templateResolver() { // SpringResourceTemplateResolver automatically integrates with Spring\'s // own // resource resolution infrastructure, which is highly recommended. SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); templateResolver.setApplicationContext(this.applicationContext); templateResolver.setPrefix("/WEB-INF/templates/"); templateResolver.setSuffix(".html"); // HTML is the default value, added here for the sake of clarity. // 模板解析模式使用HTML模式 templateResolver.setTemplateMode(TemplateMode.HTML); // Template cache is true by default. Set to false if you want // templates to be automatically updated when modified. // 是否缓存模板,默认是true,不过在调试的时候最好是false,因为模板随时需要改变 templateResolver.setCacheable(false); templateResolver.setCharacterEncoding("UTF-8"); return templateResolver; } /** * thymeleaf的模板引擎 * * @return */ @Bean public SpringTemplateEngine templateEngine() { // SpringTemplateEngine automatically applies SpringStandardDialect and // enables Spring\'s own MessageSource message resolution mechanisms. SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); // Enabling the SpringEL compiler with Spring 4.2.4 or newer can // speed up execution in most scenarios, but might be incompatible // with specific cases when expressions in one template are reused // across different data types, so this flag is "false" by default // for safer backwards compatibility. templateEngine.setEnableSpringELCompiler(true); return templateEngine; } /** * thymeleaf的视图解析器 * * @return */ @Bean public ThymeleafViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); viewResolver.setCharacterEncoding("UTF-8"); return viewResolver; } }
四、spring注解配置类
package com.test.dao.configure; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import com.alibaba.druid.pool.DruidDataSource; @Configuration @ComponentScan(basePackages={"com.test.service"}) @PropertySource("classpath:jdbc.properties") public class ApplicationConfigure { @Autowired Environment env; //配置数据源 @Bean(name="dataSource") public DataSource dataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl(env.getProperty("jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.username")); dataSource.setPassword(env.getProperty("jdbc.password")); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); return dataSource; } //配置事物 @Bean(name="txManager") public DataSourceTransactionManager txManager() { DataSourceTransactionManager txM = new DataSourceTransactionManager(); txM.setDataSource(dataSource()); return txM; } }
五、实体类
package com.test.entity; public class User { private Integer id; private String username; public User() { } public User(Integer id, String username) { this.id = id; this.username = username; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((username == null) ? 0 : username.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; } @Override public String toString() { return "User [id=" + id + ", username=" + username + "]"; } }
六、controller
package com.test.controller; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.test.entity.User; import com.test.service.IndexService; @Controller public class Indexer { @Autowired private IndexService service; @RequestMapping(value="/") public String index(Model model, HttpSession session) { List<User> users = service.findAll(); model.addAttribute("users", users); return "thymeleaf"; } }
七、service类
package com.test.service.impl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.test.entity.User; import com.test.service.IndexService; @Service public class IndexServiceImpl extends JdbcTemplate implements IndexService { @Autowired public IndexServiceImpl(DataSource dataSource) { super(dataSource); } @Transactional(transactionManager="txManager") public List<User> findAll() { String sql = "select id,username from t_user"; return this.query(sql, new Object[]{}, new RowMapper<User>(){ @Override public User mapRow(ResultSet rs, int rowNum) throws SQLException { User user = new User(rs.getInt("id"), rs.getString("username")); System.out.println(user); return user; } }); } }
八、html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"><head> <meta charset="UTF-8"> <title>spring thymeleaf Integrating</title> </head> <body> <table> <tr> <th>ID</th> <th>username</th> </tr> <tr th:each="user,userStat : ${users}"> <td th:text="${user.id}">ID</td> <td th:text="${user.username}">username</td> </tr> </table> </body> </html>
以上是关于Integrating Thymeleaf with Spring的主要内容,如果未能解决你的问题,请参考以下文章
[Spring boot] Integrating with h2 database
Integrating morphology and phylogenomics supports a terrestrial origin of insect flight
论文阅读Integrating Tree Path in Transformer for Code Representation
论文阅读Integrating Tree Path in Transformer for Code Representation
论文阅读Integrating Tree Path in Transformer for Code Representation
论文笔记:Hierarchical Deep Reinforcement Learning:Integrating Temporal Abstraction and Intrinsic