SSM整合之 XML + 注解(已整合)
概述: 本文的SSM项目搭建整合Spring、SpringMVC、MyBatis是完整模式
1. SSM整合项目环境
开发环境: Jdk1.8_261, Windows10, Maven3.63, Idea2020.1
2. 整体目录结构
1) 项目结构
src.main
java.com.xxx resource
com.xxx.dao
applicationContext.xml jdbc.properties spring-mvc.xml webapp
src.test
java
resource
applicationContext.xml jdbc.properties spring-mvc.xml target pom.xml
2) 包结构
com.xxx.controller
interceptor
ProjectExceptionAdvice.java results
UserController.java com.xxx.dao
com.xxx.domain
com.xxx.service
system.exception
BusinessException.java SystemException.java
3) ssm_db 之 user表
CREATE TABLE `user` (
`uuid` int(11) NOT NULL AUTO_INCREMENT,
`userName` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`realName` varchar(100) DEFAULT NULL,
`gender` int(1) DEFAULT NULL,
`birthday` date DEFAULT NULL,
PRIMARY KEY (`uuid`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8
3. 导入项目所需 jar 包坐标 - pom.xml
<?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.xxx</ groupId>
< artifactId> stu-ssm-base02</ artifactId>
< version> 1.0-SNAPSHOT</ version>
< packaging> war</ packaging>
< properties>
< project.build.sourceEncoding> UTF-8</ project.build.sourceEncoding>
< maven.compiler.source> 1.8</ maven.compiler.source>
< maven.compiler.target> 1.8</ maven.compiler.target>
</ properties>
< dependencies>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-context</ artifactId>
< version> 5.1.9.RELEASE</ version>
</ dependency>
< dependency>
< groupId> org.mybatis</ groupId>
< artifactId> mybatis</ artifactId>
< version> 3.5.3</ version>
</ dependency>
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
< version> 5.1.47</ version>
</ dependency>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-jdbc</ artifactId>
< version> 5.1.9.RELEASE</ version>
</ dependency>
< dependency>
< groupId> org.mybatis</ groupId>
< artifactId> mybatis-spring</ artifactId>
< version> 2.0.3</ version>
</ dependency>
< dependency>
< groupId> com.alibaba</ groupId>
< artifactId> druid</ artifactId>
< version> 1.1.16</ version>
</ dependency>
< dependency>
< groupId> com.github.pagehelper</ groupId>
< artifactId> pagehelper</ artifactId>
< version> 5.1.2</ version>
</ dependency>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-webmvc</ artifactId>
< version> 5.1.9.RELEASE</ version>
</ dependency>
< dependency>
< groupId> com.fasterxml.jackson.core</ groupId>
< artifactId> jackson-databind</ artifactId>
< version> 2.9.0</ version>
</ dependency>
< dependency>
< groupId> com.fasterxml.jackson.core</ groupId>
< artifactId> jackson-core</ artifactId>
< version> 2.9.0</ version>
</ dependency>
< dependency>
< groupId> com.fasterxml.jackson.core</ groupId>
< artifactId> jackson-annotations</ artifactId>
< version> 2.9.0</ version>
</ dependency>
< dependency>
< groupId> javax.servlet</ groupId>
< artifactId> javax.servlet-api</ artifactId>
< version> 3.1.0</ version>
< scope> provided</ scope>
</ dependency>
< dependency>
< groupId> junit</ groupId>
< artifactId> junit</ artifactId>
< version> 4.12</ version>
</ dependency>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-test</ artifactId>
< version> 5.1.9.RELEASE</ version>
</ dependency>
</ dependencies>
< build>
< plugins>
< plugin>
< groupId> org.apache.tomcat.maven</ groupId>
< artifactId> tomcat7-maven-plugin</ artifactId>
< version> 2.1</ version>
< configuration>
< port> 80</ port>
< uriEncoding> utf-8</ uriEncoding>
< path> /</ path>
</ configuration>
</ plugin>
</ plugins>
</ build>
</ project>
4. 相关配置文件
1) MyBatis的mapper映射配置文件 - UserDao.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 = " com.xxx.dao.UserDao" >
< insert id = " save" parameterType = " user" >
insert into user(userName,password,realName,gender,birthday)values(#{userName},#{password},#{realName},#{gender},#{birthday})
</ insert>
< delete id = " delete" parameterType = " int" >
delete from user where uuid = #{uuid}
</ delete>
< update id = " update" parameterType = " user" >
update user set userName=#{userName},password=#{password},realName=#{realName},gender=#{gender},birthday=#{birthday} where uuid=#{uuid}
</ update>
< select id = " get" resultType = " user" parameterType = " int" >
select * from user where uuid = #{uuid}
</ select>
< select id = " getAll" resultType = " user" >
select * from user
</ select>
< select id = " getByUserNameAndPassword" resultType = " user" >
select * from user where userName=#{userName} and password=#{password}
</ select>
</ mapper>
2) Spring配置文件(整合MyBatis和SpringMvc) - applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans"
xmlns: context= " http://www.springframework.org/schema/context"
xmlns: tx= " http://www.springframework.org/schema/tx"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd" >
< context: component-scan base-package = " com.xxx" />
< tx: annotation-driven transaction-manager = " txManager" />
< context: property-placeholder location = " classpath*:jdbc.properties" />
< bean id = " dataSource" class = " com.alibaba.druid.pool.DruidDataSource" >
< property name = " driverClassName" value = " ${jdbc.driver}" />
< property name = " url" value = " ${jdbc.url}" />
< property name = " username" value = " ${jdbc.username}" />
< property name = " password" value = " ${jdbc.password}" />
</ bean>
< bean class = " org.mybatis.spring.SqlSessionFactoryBean" >
< property name = " dataSource" ref = " dataSource" />
< property name = " typeAliasesPackage" value = " com.xxx.domain" />
< property name = " plugins" >
< array>
< bean class = " com.github.pagehelper.PageInterceptor" >
< property name = " properties" >
< props>
< prop key = " helperDialect" > mysql</ prop>
< prop key = " reasonable" > true</ prop>
</ props>
</ property>
</ bean>
</ array>
</ property>
</ bean>
< bean class = " org.mybatis.spring.mapper.MapperScannerConfigurer" >
< property name = " basePackage" value = " com.xxx.dao" />
</ bean>
< bean id = " txManager" class = " org.springframework.jdbc.datasource.DataSourceTransactionManager" >
< property name = " dataSource" ref = " dataSource" />
</ bean>
</ beans>
3) SpringMVC配置文件 - spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
< beans xmlns = " http://www.springframework.org/schema/beans"
xmlns: context= " http://www.springframework.org/schema/context"
xmlns: mvc= " http://www.springframework.org/schema/mvc"
xmlns: xsi= " http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation= " http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" >
< mvc: annotation-driven/>
< context: component-scan base-package = " com.xxx.controller" />
</ beans>
4) JDBC配置文件 - jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
5. 整体项目环境搭建(已整合)
1) domain 层 - User.java
package com. xxx. domain;
import com. fasterxml. jackson. annotation. JsonFormat;
import org. springframework. format. annotation. DateTimeFormat;
import java. util. Date;
public class User {
private Integer uuid;
private String userName;
private String password;
private String realName;
private Integer gender;
@DateTimeFormat ( pattern = "yyyy/MM/dd" )
@JsonFormat ( pattern = "yyyy/MM/dd" )
private Date birthday;
public User ( ) {
}
public User ( Integer uuid, String userName, String password, String realName, Integer gender, Date birthday) {
this . uuid = uuid;
this . userName = userName;
this . password = password;
this . realName = realName;
this . gender = gender;
this . birthday = birthday;
}
public Integer getUuid ( ) {
return uuid;
}
public void setUuid ( Integer uuid) {
this . uuid = uuid;
}
public String getUserName ( ) {
return userName;
}
public void setUserName ( String userName) {
this . userName = userName;
}
public String getPassword ( ) {
return password;
}
public void setPassword ( String password) {
this . password = password;
}
public String getRealName ( ) {
return realName;
}
public void setRealName ( String realName) {
this . realName = realName;
}
public Integer getGender ( ) {
return gender;
}
public void setGender ( Integer gender) {
this . gender = gender;
}
public Date getBirthday ( ) {
return birthday;
}
public void setBirthday ( Date birthday) {
this . birthday = birthday;
}
@Override
public String toString ( ) {
return "User{" +
"uuid=" + uuid +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
", realName='" + realName + '\'' +
", gender=" + gender +
", birthday=" + birthday +
'}' ;
}
}
2) dao 层 - UserDao.java
package com. xxx. dao;
import com. xxx. domain. User;
import org. apache. ibatis. annotations. Param;
import java. util. List;
public interface UserDao {
boolean save ( User user) ;
boolean update ( User user) ;
boolean delete ( Integer id) ;
User get ( Integer id) ;
List< User> getAll ( ) ;
User getByUserNameAndPassword ( @Param ( "userName" ) String userName, @Param ( "password" ) String password) ;
}
3) service 层 - UserService.java
package com. xxx. service;
import com. github. pagehelper. PageInfo;
import com. xxx. domain. User;
@Transactional ( rollbackFor = Exception. class )
public interface UserService {
boolean save ( User user) ;
boolean update ( User user) ;
boolean delete ( Integer id) ;
User get ( Integer id) ;
PageInfo< User> getAll ( int page, int size) ;
User login ( String userName, String password) ;
}
4) service 实现类 - UserServiceImpl.java
package com. xxx. service. impl;
import com. github. pagehelper. Page;
import com. github. pagehelper. PageHelper;
import com. github. pagehelper. PageInfo;
import com. xxx. dao. UserDao;
import com. xxx. domain. User;
import com. xxx. service. UserService;
import org. springframework. beans. factory. annotation. Autowired;
import org. springframework. stereotype. Service;
import java. util. List;
@Service ( "userService" )
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public boolean save ( User user) {
return userDao. save ( user) ;
}
@Override
public boolean update ( User user) {
return userDao. update ( user) ;
}
@Override
public boolean delete ( Integer id) {
return userDao. delete ( id) ;
}
@Override
public User get ( Integer id) {
return userDao. get ( id) ;
}
@Override
public PageInfo< User> getAll ( int page, int size) {
PageHelper. startPage ( page, size) ;
List< User> all = userDao. getAll ( ) ;
return new PageInfo < > ( all) ;
}
@Override
public User login ( String userName, String password) {
return userDao. getByUserNameAndPassword ( userName, password) ;
}
}
5) controller 层 - UserController.java
package com. xxx. controller;
import com. github. pagehelper. PageInfo;
import com. xxx. controller. results. Code;
import com. xxx. controller. results. Result;
import com. xxx. domain. User;
import com. xxx. service. UserService;
import com. xxx. system. exception. BusinessException;
import org. springframework. beans. factory. annotation. Autowired;
import org. springframework. web. bind. annotation. *;
@RestController
@RequestMapping ( "/user" )
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public Result save ( User user) {
boolean saveFlag = userService. save ( user) ;
return new Result ( saveFlag ? Code. SAVE_OK : Code. SAVE_ERROR, saveFlag) ;
}
@PutMapping ( "/f" )
public Result updateForm ( User user) {
System. out. println ( user) ;
boolean updateFlag = userService. update ( user) ;
return new Result ( updateFlag ? Code. UPDATE_OK : Code. UPDATE_ERROR, updateFlag) ;
}
@PutMapping ( "/j" )
public Result updateJson ( @RequestBody User user) {
System. out. println ( "异步请求" + user) ;
boolean updateFlag = userService. update ( user) ;
return new Result ( updateFlag ? Code. UPDATE_OK : Code. UPDATE_ERROR, updateFlag) ;
}
@DeleteMapping ( "/{uuid}" )
public Result delete ( @PathVariable int uuid) {
boolean deleteFlag = userService. delete ( uuid) ;
return new Result ( deleteFlag ? Code. DELETE_OK : Code. DELETE_ERROR, deleteFlag) ;
}
@GetMapping ( "/login" )
public Result login ( String userName, String password) {
User login = userService. login ( userName, password) ;
return new Result ( login != null ? Code. GET_OK : Code. GET_ERROR, login != null, login) ;
}
@GetMapping ( "/{uuid}" )
public Result get ( @PathVariable Integer uuid) {
User user = userService. get ( uuid) ;
if ( uuid == 10 ) {
throw new BusinessException ( "查询出错啦,请重试!" , Code. GET_ERROR) ;
}
return new Result ( user == null ? Code. GET_OK : Code. GET_ERROR, user == null, user) ;
}
@GetMapping ( "/{page}/{size}" )
public Result getAll ( @PathVariable int page, @PathVariable int size) {
PageInfo< User> all = userService. getAll ( page, size) ;
return new Result ( all. getList ( ) != null ? Code. GET_OK : Code. GET_ERROR, all. getList ( ) != null, all) ;
}
}
6) 数据封装与数据响应编码
(1) Result.java
package com. xxx. controller. results;
public class Result {
private Integer code;
private boolean flag;
private Object data;
private String message;
public Result ( Integer code, boolean flag) {
this . code = code;
this . flag = flag;
}
public Result ( Integer code, boolean flag, Object data) {
this . code = code;
this . flag = flag;
this . data = data;
}
public Result ( Integer code, boolean flag, String message) {
this . code = code;
this . flag = flag;
this . message = message;
}
public boolean isFlag ( ) {
return flag;
}
public void setFlag ( boolean flag) {
this . flag = flag;
}
public Integer getCode ( ) {
return code;
}
public void setCode ( Integer code) {
this . code = code;
}
public Object getData ( ) {
return data;
}
public void setData ( Object data) {
this . data = data;
}
public String getMessage ( ) {
return message;
}
public void setMessage ( String message) {
this . message = message;
}
@Override
public String toString ( ) {
return "Result{" +
"code=" + code +
", data=" + data +
", message='" + message + '\'' +
'}' ;
}
}
(2) Code.java
package com. xxx. controller. results;
public class Code {
public static final Integer SAVE_OK = 20011 ;
public static final Integer UPDATE_OK = 20021 ;
public static final Integer DELETE_OK = 20031 ;
public static final Integer GET_OK = 20041 ;
public static final Integer SAVE_ERROR = 20010 ;
public static final Integer UPDATE_ERROR = 20020 ;
public static final Integer DELETE_ERROR = 20030 ;
public static final Integer GET_ERROR = 20040 ;
}
7) 自定义异常类
(1) 业务异常处理类 - BusinessException.java
package com. xxx. system. exception;
public class BusinessException extends RuntimeException {
private Integer code;
public Integer getCode ( ) {
return code;
}
public void setCode ( Integer code) {
this . code = code;
}
public BusinessException ( Integer code) {
super ( ) ;
this . code = code;
}
public BusinessException ( String message, Integer code) {
super ( message) ;
this . code = code;
}
public BusinessException ( String message, Throwable cause, Integer code) {
super ( message, cause) ;
this . code = code;
}
public BusinessException ( Throwable cause, Integer code) {
super ( cause) ;
this . code = code;
}
protected BusinessException ( String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Integer code) {
super ( message, cause, enableSuppression, writableStackTrace) ;
this . code = code;
}
}
(2) 系统异常处理类(未实现 - 同业务异常) - SystemException.java
package com. xxx. system. exception;
public class SystemException {
}
8) 拦截器
(1) 项目异常拦截类 - ProjectExceptionAdvice.java
package com. xxx. controller. interceptor;
import com. xxx. controller. results. Result;
import com. xxx. system. exception. BusinessException;
import org. springframework. stereotype. Component;
import org. springframework. web. bind. annotation. ControllerAdvice;
import org. springframework. web. bind. annotation. ExceptionHandler;
import org. springframework. web. bind. annotation. ResponseBody;
@Component
@ControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler ( BusinessException. class )
@ResponseBody
public Result doBusinessException ( BusinessException e) {
return new Result ( e. getCode ( ) , false , e. getMessage ( ) ) ;
}
}