这个是基于注解的配置方式,基于配置文件的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. CI控制器

    当控制器要继承自定义的控制器的时候,有特定的定义: application/core/MY_Controller <?php class MY_Controller extends CI_Con ...

  2. Git及基础命令的介绍以及如何向本地仓库添加文件

    在介绍Git的使用之前,我们得要先来了解一下Git.那么什么是Git? Git是一个版本管理工具(VCS),具有以下的特点: 分布式版本控制: 多个开发人员协调工作: 有效监听谁做的修改: 本地及远程 ...

  3. django-haystack+whoosh+jieba实现中文全文搜索

    先上效果图 附上个人网站:https://liyuankun.cn 安装依赖库 注意:这里我们不安装django-haystack,因为要添加中文分词的功能很麻烦,所以我直接集成了一个中文的djang ...

  4. Windows 10使用Tesseract-OCR出现WindowsError: [Error 2]

    Tesseract-OCR安装时默认安装在x86的目录下,手动添加环境变量此电脑-->属性-->高级系统设置-->环境变量,点击系统变量里的Path, 点击编辑,在编辑环境变量界面中 ...

  5. 如何使用共享网卡的NAT模式配置VMware12中的CentOS6.7的上网功能

    1.首先共享网卡的NAT模式是通过win10中的VMnet8来通信的,如下双击VMnet8 2.点击[详细信息]查看VMnet8的IPV4地址为192.168.232.110,掩码为255.255.2 ...

  6. HTTP请求代理类(GET 、 POST 、PUT 、DELETE)

    package com.jm.http.tools; import java.io.BufferedReader; import java.io.IOException; import java.io ...

  7. HTTP 学习笔记02

    请求行 格式:请求方式  资源路径  HTTP版本号 HTTP1.1 还需要 [host] 例:GET   /test.html   HTTP/1.0 GET   /test.html   HTTP/ ...

  8. 计算机以及Python的初始

    电脑的介绍 CPU:中央处理器,相当于人类的大脑 内存:暂时储存数据,速度快,造价高,断电后丢失 硬盘:长期储存数据.速度相对慢,造价相对低 操作系统:一个软件,连接计算机硬件和系统中的软件. Pyt ...

  9. elasticsearch 集群部署,版本 5.5.0

    准备说明: 两台服务器 Ip分别为 192.168.239.78(主),192.168.239.49(从) 主服务器上配置如下:1.上传es5.5.0版本至主服务器2.解压 unzipunzip el ...

  10. MyBatis 核心配置综述之Executor

    目录 MyBatis四大组件之 Executor执行器 Executor的继承结构 Executor创建过程以及源码分析 Executor接口的主要方法 Executor 的现实抽象 上一篇我们对Sq ...