SpringMVC整合thymeleaf
- SSM+thymeleaf
1.构建maven项目
- 使用工具向导构建就可以了,打包格式改为war
2.pom.xml添加依赖
<dependencies>
<!--springmvc的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!--rest风格使用-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<!--mybatis spring的插件,将mybatis交给spring来管理-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--spring的单元测试-->
<!--<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>-->
<!--单元测试-->
<!--<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>-->
<!--spring jdbc,包含事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!-- spring aop的面向切面的配置-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.0</version>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</version>
</dependency>
<!--日志信息-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--lombok,特别注意,与maven的tomcat插件冲突时,将scope设置为provided-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<!--为了使用@Resource注解-->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<!--thymeleaf依赖-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
</dependencies>
<build>
<!--不过滤java下的xml文件-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- 添加tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8080</port>
</configuration>
</plugin>
</plugins>
</build>
- 修改之后的pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ym</groupId>
<artifactId>SpringMVC_thymeleaf</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!--springmvc的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!--rest风格使用-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<!--mybatis spring的插件,将mybatis交给spring来管理-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--spring的单元测试-->
<!--<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>-->
<!--单元测试-->
<!--<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>-->
<!--spring jdbc,包含事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!-- spring aop的面向切面的配置-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.0</version>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</version>
</dependency>
<!--日志信息-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--lombok,特别注意,与maven的tomcat插件冲突时,将scope设置为provided-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<!--为了使用@Resource注解-->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<!--thymeleaf依赖-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
</dependencies>
<build>
<!--不过滤java下的xml文件-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- 添加tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8080</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
3.在resources包下添加SSM的配置文件db.perperties;log4j.properties;mybatis-config.xml;spring-mvc.xml;spring-mybatis.xml
- db.properties
url=jdbc:mysql://localhost:3307/datatest?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
driver=com.mysql.cj.jdbc.Driver
uname=root
upass=root
maxActive=50
minIdle=1
- log4j.properties
# 全局日志配置
# 共有四个级别 ERROE,DEBUG,WARN,INFO
log4j.rootLogger=ERROR, stdout, F
# MyBatis 日志配置,可以指定到包下,也可以指定到类上,也可以指定到类中的某一个方法
log4j.logger.com.yanm.dao.IUserDao=TRACE
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%6p [%t] - %m%n
#打印到文件myproj.log中--专门为DAO层服务
log4j.appender.F = org.apache.log4j.DailyRollingFileAppender
log4j.appender.F.File =myproj.log
log4j.appender.F.Append = true
log4j.appender.F.Threshold = ERROE
log4j.appender.F.layout=org.apache.log4j.PatternLayout
log4j.appender.F.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss}-[%p %F\:%L] %m%n
- mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--给当前mybatis项目添加日志功能,采用第三方日志jar包-->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
</configuration>
- spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--设置ssm项目的注解配置-->
<context:annotation-config /> <!--与下面的包扫描重复了-->
<!--设置包扫描,分别扫描controller和service包-->
<context:component-scan base-package="com.ym.controller"/>
<context:component-scan base-package="com.ym.service" />
<!--注解驱动-->
<mvc:annotation-driven />
<!--配置默认资源可以被访问-->
<mvc:default-servlet-handler />
<!--引入spring和mybatis的整合文件-->
<import resource="classpath:spring-mybatis.xml" />
<!--模板解析器-->
<bean id="str" class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML" />
</bean>
<!--模板引擎-->
<bean id="ste" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="str" />
</bean>
<!--视图解析器-->
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="ste" />
<property name="characterEncoding" value="UTF-8" />
<property name="contentType" value="text/html;charset=UTF-8"/>
</bean>
</beans>
- spring-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--引入数据库的配置文件信息-->
<context:property-placeholder location="classpath:db.properties" />
<!--druid数据源-->
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${url}" />
<property name="driverClassName" value="${driver}" />
<property name="username" value="${uname}" />
<property name="password" value="${upass}" />
</bean>
<bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.ym.pojo" />
<property name="mapperLocations" value="classpath*:dao/*Dao.xml" />
<property name="dataSource" ref="ds" />
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ym.dao" />
<property name="sqlSessionFactoryBeanName" value="ssfb"/>
</bean>
<!--配置事务管理器-->
<bean id="dstm" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="ds"/>
</bean>
<!--声明事务的实现方式
以这些关键字开头的方法分别设置事务的隔离级别以及出错后的操作-->
<tx:advice id="tx" transaction-manager="dstm">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="mpt" expression="execution(* com.ym.service.*.*(..))"/>
<aop:advisor advice-ref="tx" pointcut-ref="mpt"/>
</aop:config>
<!--添加扫描,对service层进行单元测试的时候,一定要定位到service包下-->
<context:component-scan base-package="com.ym.service" />
</beans>
4.pojo层User
package com.ym.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int uid;
private String name;
private String sex;
private int age;
private String address;
}
5.dao层接口
- 接口上需要@Mapper注解
package com.ym.dao;
import com.ym.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface IUserDao {
List<User> getAllUsers();
User getUserByUid(int uid);
int editUser(User user);
int deleteUserByUid(int uid);
int saveUser(User user);
}
6.resources包下新建dao包,并新建与接口对应的xml文件
- UsersDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 整个映射文件为mapper节点,里面包含namespace属性 -->
<mapper namespace="com.ym.dao.IUserDao">
<sql id="all">
select * from users
</sql>
<select id="getAllUsers" resultType="user">
<include refid="all" />
</select>
<select id="getUserByUid" resultType="user">
select * from users where uid=#{uid}
</select>
<update id="editUser">
update users
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="sex != null and sex != ''">
sex = #{sex},
</if>
<if test="age != 0">
age = #{age},
</if>
<if test="address != null and address != ''">
address = #{address},
</if>
</set>
where uid = #{uid}
</update>
<delete id="deleteUserByUid">
delete from users where uid=#{uid}
</delete>
<insert id="saveUser">
insert into users values (default ,#{name},#{sex},#{age},#{address})
</insert>
</mapper>
7.service层接口IUserService.java
package com.ym.service;
import com.ym.pojo.User;
import java.util.List;
public interface IUserService {
List<User> getAllUsers();
User getUserByUid(int uid);
int editUser(User user);
int deleteUserByUid(int uid);
int saveUser(User user);
}
8.service层接口的实现类UserService.java
package com.ym.service.impl;
import com.ym.dao.IUserDao;
import com.ym.pojo.User;
import com.ym.service.IUserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserService implements IUserService {
@Resource
private IUserDao userDao;
@Override
public List<User> getAllUsers() {
return userDao.getAllUsers();
}
@Override
public User getUserByUid(int uid) {
return userDao.getUserByUid(uid);
}
@Override
public int editUser(User user) {
return userDao.editUser(user);
}
@Override
public int deleteUserByUid(int uid) {
return userDao.deleteUserByUid(uid);
}
@Override
public int saveUser(User user) {
return userDao.saveUser(user);
}
}
9.controller层的UserController.java
package com.ym.controller;
import com.ym.pojo.User;
import com.ym.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
@Controller
public class UserController {
@Resource
private IUserService userService;
@GetMapping("/getAllUser")
@ResponseBody
public List<User> getAllUser(){
List<User> users = userService.getAllUsers();
return users;
}
@GetMapping("/allUser")
public String queryAllUser(Model model){
List<User> users = userService.getAllUsers();
model.addAttribute("users",users);
return "user";
}
@GetMapping("/updateUsers/{uid}")
public String queryUserByUid(@PathVariable int uid, Model model){
User user = userService.getUserByUid(uid);
model.addAttribute("user",user);
return "userInfo";
}
@PostMapping("/editUser")
public String editUser(User user){
int i = userService.editUser(user);
if (i>0){
return "redirect:/allUser";
}else {
return "forward:/WEB-INF/error/errorPage.html";
}
}
@GetMapping("/deleteUser/{uid}")
public String deleteUser(@PathVariable int uid){
int i = userService.deleteUserByUid(uid);
if (i>0){
return "redirect:/allUser";
}else {
return "forward:/WEB-INF/error/errorPage.html";
}
}
@GetMapping("/toAdduser")
public String toAdduser(){
return "adduser";
}
@PostMapping("/saveUser")
public String saveUser(User user){
int i = userService.saveUser(user);
if (i>0){
return "redirect:/allUser";
}else {
return "forward:/WEB-INF/error/errorPage.html";
}
}
}
10.新建webapp;WEB-INF包,并新建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_4_0.xsd"
version="4.0">
<!--配置springmvc-->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--
使用springk框架写好的中文乱码过滤器来实现乱码的处理
-->
<filter>
<filter-name>encode</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>encode</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
11.前端页面
-
需要在html的头文件中添加代码
<html lang="en" xmlns:th="http://www.thymeleaf.org">
-
user.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>this is thymeleaf page</h1>
<table width="80%" align="center" border="1">
<tr>
<th>编号</th>
<th>名称</th>
<th>性别</th>
<th>年龄</th>
<th>地址</th>
<th>修改 <a href="/toAdduser" th:href="@{/toAdduser}">ADD</a></th>
</tr>
<tbody>
<tr th:each="u:${users}">
<td th:text="${u.uid}">默认值</td>
<td th:text="${u.name}">默认值</td>
<td th:text="${u.sex}">默认值</td>
<td th:text="${u.age}">默认值</td>
<td th:text="${u.address}">默认值</td>
<td>
<a href="/updateUsers/1" th:href="@{'/updateUsers/'+${u.uid}}">update</a>
<a href="/deleteUser/1" th:href="@{'/deleteUser/'+${u.uid}}">delete</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
- userInfo.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>this is userInfo page</h1>
<form th:action="@{/editUser}" th:method="post" th:object="${user}">
编号: <input type="text" name="uid" readonly="readonly" value="" th:value="*{uid}" > <br>
姓名: <input type="text" name="name" value="" th:value="*{name}" > <br>
性别: <input type="text" name="sex" value="" th:value="*{sex}" > <br>
年龄: <input type="number" name="age" value="" th:value="*{age}" > <br>
地址: <input type="text" name="address" value="" th:value="*{address}" > <br>
<input type="submit" value="update">
</form>
</body>
</html>
- adduser.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>ADD</title>
</head>
<body>
<form th:action="@{/saveUser}" th:method="post" >
姓名: <input type="text" name="name"> <br>
性别: <input type="text" name="sex" > <br>
年龄: <input type="number" name="age"> <br>
地址: <input type="text" name="address"> <br>
<input type="submit" value="ADD">
</form>
</body>
</html>
- errorPage.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>抱歉,页面出错了</h1>
</body>
</html>
网友评论