这个是基于注解的配置方式,基于配置文件的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. Jenkins的安装与使用(一)

    jenkins是一个广泛用于持续构建的可视化web工具,持续构建说得更直白点,就是各种项目的"自动化"编译.打包.分发部署.jenkins可以很好的支持各种语言(比如:java, ...

  2. java开发工具必备神器——Notepad++和jd-gui下载安装使用

    Notepad++是 Windows操作系统下的一套文本编辑器,有完整的中文化接口及支持多国语言编写的功能(UTF8技术).除了可以用来制作一般的纯文字说明文件,也十分适合编写计算机程序代码.Note ...

  3. java代码书写易犯错误

    java代码书写易犯错误: 常见报错: 控制台报错: 找不到或无法加载主类 HelloWorld 原因: java.lang.NoClassDefFoundError: cn/itcast/day01 ...

  4. Qt之股票组件-股票检索--支持预览框、鼠标、键盘操作

    目录 一.感慨一下 二.效果展示 三.搜索编辑框 1.编辑框 2.预览框 四.相关文章 原文链接:Qt之股票组件-股票检索--支持预览框.鼠标.键盘操作 一.感慨一下 之前做过一款炒股软件,个人觉着是 ...

  5. Java基础介绍运行机制笔记

    1. 基础知识点图解 编程语言核心结构:变量.基本语法.分支.循环.数组.…… Java面向对象的核心逻辑:OOP.封装.继承.多态.接口…… 开发Java SE高级应用程序:异常.集合.I/O.多线 ...

  6. 分享常见的HTTP状态码

    本内容摘抄自RUNOOB.COM 当浏览一个网页时,浏览器会向网页所在服务器发出请求.当浏览器确定接收并显示网页之前,此网页所在的服务器会返回一个含有HTTP状态码(HTTP Status Code) ...

  7. Java中session与application的异同

    客户端的session 其实是标记了你的请求来自哪个浏览器 问题1:永远都一样吗? 答:重启了浏览器,你的session id就改变了, 结果会导致,再无法取回原来在服务端保存的数据. 问题2:假设客 ...

  8. leetcode 141 Linked List Cycle Hash fast and slow pointer

    Problem describe:https://leetcode.com/problems/linked-list-cycle/ Given a linked list, determine if ...

  9. 学Redis这篇就够了

    Redis 简介 Redis 优势 Redis 数据类型 string hash list set Zset 小总结 基本命令 发布订阅 简介 实例 发布订阅常用命令 事务 实例 Redis 事务命令 ...

  10. 截图编辑器 PicPick Biz v4.1.6/v5.0.3 Lite 绿色便携版

    下载地址:点我 PicPick 是由NGWIN 软件科技公司推出的一款实用的.多功能屏幕截图与图像编辑神器.软件具备屏幕截取.取色器.调色板.放大镜.标尺.量角器.坐标轴.白板等功能,支持全屏.活动窗 ...