这个是基于注解的配置方式,基于配置文件的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></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-</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 = ;
int result = ;
result = prime * result + ((id == null) ? : id.hashCode());
result = prime * result + ((username == null) ? : 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的更多相关文章

  1. Thymeleaf 集成spring

    Thymeleaf 集成spring 如需先了解Thymeleaf的单独使用,请参考<Thymeleaf模板引擎使用>一文. 依赖的jar包 Thymeleaf 已经集成了spring的3 ...

  2. 问题:Thymeleaf整合Spring Security后sec属性不起作用

    可能原因: 版本不兼容,例如2.1.x的SpringBoot不兼容3.0.4的thymeleaf-extras-springsecurity4 解决方案: 修改Spring Boot的版本为2.0.x ...

  3. spring boot(四):thymeleaf使用详解

    在上篇文章springboot(二):web综合开发中简单介绍了一下thymeleaf,这篇文章将更加全面详细的介绍thymeleaf的使用.thymeleaf 是新一代的模板引擎,在spring4. ...

  4. Thymeleaf+Spring整合

    前言 这个教程介绍了Thymeleaf与Spring框架的集成,特别是SpringMvc框架. 注意Thymeleaf支持同Spring框架的3.和4.版本的集成,但是这两个版本的支持是封装在thym ...

  5. 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 ...

  6. Spring Boot 学习笔记--整合Thymeleaf

    1.新建Spring Boot项目 添加spring-boot-starter-thymeleaf依赖 <dependency> <groupId>org.springfram ...

  7. spring boot + Thymeleaf开发web项目

    "Spring boot非常适合Web应用程序开发.您可以轻松创建自包含的HTTP应用.web服务器采用嵌入式Tomcat,或者Jetty等.大多数情况下Web应用程序将使用 spring- ...

  8. Spring boot(三)整合mybaties+thymeleaf实现基础crud

    工程结构: 首先在pom文件中引入依赖 <?xml version="1.0" encoding="UTF-8"?> <project xml ...

  9. spring boot:thymeleaf使用详解

    简单说, Thymeleaf 是一个跟 Velocity.FreeMarker 类似的模板引擎,它可以完全替代 JSP .相较与其他的模板引擎,它有如下三个极吸引人的特点: 1.Thymeleaf 在 ...

随机推荐

  1. 常用URL分享,实用地址

    常用地址 文库文档免费下载地址1:http://www.hiwenku.com/ 文库文档免费下载下载2:http://www.20009.net/wk.html google地图拾取器:http:/ ...

  2. Elasticsearch-head插件使用小结

    1.ElasticSearch-head是什么? ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口.Elasti ...

  3. Windows新终端中玩转ASCII和Emoji游戏的正确姿势

    Windows新终端中玩转ASCII和Emoji游戏的正确姿势 前一段时间,我搬运了几个Windows Terminal中玩游戏的视频,详情请看 发布在即!来一睹官方团队如何玩转 Windows Te ...

  4. Qemu搭建ARM vexpress开发环境(三)----NFS网络根文件系统

    Qemu搭建ARM vexpress开发环境(三)----NFS网络根文件系统 标签(空格分隔): Qemu ARM Linux 经过上一篇<Qemu搭建ARM vexpress开发环境(二)- ...

  5. C语言-main方法的两个参数是干什么的?

    大家都知道C语言的main方法怎么写的吧!但你们知道mian方法里的参数的含义吗? 代码如下: int main(int argc,char *argv[]){ //argc是传进的参数个数 //ar ...

  6. kubernetes实战篇之创建一个只读权限的用户

    系列目录 上一节我们讲解到了如何限制用户访问dashboard的权限,这节我们讲解一个案例:如何创建一个只读权限的用户. 虽然可以根据实际情况灵活创建各种权限用户,但是实际生产环境中往往只需要两个就行 ...

  7. 【搬家啦】2019年06月20日csdn难民来报道啦~

    原博地址:https://blog.csdn.net/the_fool_

  8. QT MSVC编译中文乱码问题

    两种解决方案: 1,在文件头添加 #if _MSC_VER >= 1600 #pragma execution_character_set("utf-8") #endif 注 ...

  9. 关于svn服务部署方案

    本文只记录我的笔记 首先, 我是个懒人, 写好了shell, 直接上传把 安装包:SvnPackages-chenglee 第一, 无非就是搞掂依赖这一块 #********************* ...

  10. Hash碰撞概率

    计算Hash冲突的概率 虽然已经很多可以选择的Hash函数,但创建一个好的Hash函数仍然是一个活跃的研究领域.一些Hash函数是快的,一些是慢的,一些Hash值均匀地分布在值域上,一些不是.对于我们 ...