这个是基于注解的配置方式,基于配置文件的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. sql关联查询—将一个表的查询结果作为新表进行查询操作

    例题:#  各个部门中 最高工资中最低的那个部门的 最低工资是多少? 先考虑取得各个部门最高工资 SELECT MAX(salary) AS max_salary,e.`department_id` ...

  2. 【Webkit Blog翻译】深入研究WebRTC | 内有福利

    本文译自 A Closer Look Into WebRTC” 我们在最近的一篇 WebKit博客中宣布了对High Sierra平台和iOS中Safari的WebRTC支持.现在,我们希望能够带领大 ...

  3. linux 下 设置 MySQL8 表名大小写不敏感方法,解决设置后无法启动 MySQL 服务的问题

    在安装完成之后,初始化数据库之前,修改 my.cnf 打开mysql配置文件 vim /etc/my.cnf 在尾部追加一行 lower_case_table_names=1 并保存,然后再初始化数据 ...

  4. zphp源码分析(一)

    zphp是一款轻量级的php服务端框架,是swoole官方开发的.可以用来开发web应用和网络服务. 安装: 可以通过composer安装, { "require": { &quo ...

  5. ajax:error:function (XMLHttpRequest, textStatus, errorThrown) 中status、readyState和textStatus状态意义

    textStatus: "timeout", 超时 "error", 出错 "notmodified" , 未修改 "parser ...

  6. PATB 1004 成绩排名 (20)

    1004. 成绩排名 (20) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 作者 CHEN, Yue 读入n名学生的姓名.学号.成绩,分 ...

  7. Mac上PyCharm运行多进程报错的解决方案

    Mac上PyCharm运行多进程报错的解决方案 运行时报错 may have been in progress in another thread when fork() was called. We ...

  8. Linux系统中sysctl命令详解

    sysctl命令用于运行时配置内核参数,这些参数位于/proc/sys目录下.sysctl配置与显示在/proc/sys目录中的内核参数.可以用sysctl来设置或重新设置联网功能,如IP转发.IP碎 ...

  9. java与WebService对接案例--生成代码方法

    前端时间出差做项目,因为我们给对三方工厂做Mes项目,其中有一个报工环节,需要我们的Mes中将产品提交到他们的U9(Erp)上,但是由于u9是用友的产品,用c#写的,而我是用java写的,那么WebS ...

  10. 半小时学会V语言

    半小时学会V语言 1. V语言简介 V是一个静态类型.编译型的编程语言,目标是构建可维护软件.与Go语言相似,并受Oberon,Rust和Swift语言影响.V语言非常简单,只需要半小时就能学会这门语 ...