1.项目基础结构搭建(part1)
创建项目,组织项目结构,创建包
创建表与实体类
创建三层架构对应的模块,接口与实体类,建立关联关系
数据层接口(代理自动创建实体类)
业务层接口+业务层实现类
表现层类
user数据库
CREATE TABLE user (
uuid INT(10) 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=15 DEFAULT CHARSET=utf8
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>MVCssm</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--junit单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<!--spring整合junit-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.19.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.2.1</version>
</dependency>
<!--servlet3.1规范的坐标-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jsp坐标-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<!--spring web坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--springmvc坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--json相关坐标3个-->
<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-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<!--导入校验的jar303规范-->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!--构建-->
<build>
<!--设置插件-->
<plugins>
<!--具体的插件配置-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.domain;
import java.util.Date;
public class User {
private Integer uuid;
private String userName;
private String password;
private String realName;
private Integer gender;
private Date 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 +
'}';
}
}
package com.dao;
import com.domain.User;
import java.util.List;
public interface UserDao {
//添加用户
public boolean save(User user);
//修改用户
public boolean update(User user);
//删除用户
public boolean delete(Integer uuid);
//查询单个用户信息
public User get(Integer uuid);
//查询全部用户信息
public List<User> getAll();
//根据用户密码查询用户信息
public User getByUserNameAndPassword(String userName,String password);
}
package com.service;
import com.domain.User;
import java.util.List;
public interface UserService {
//添加用户
public boolean save(User user);
//修改用户
public boolean update(User user);
//删除用户
public boolean delete(Integer uuid);
//查询单个用户信息
public User get(Integer uuid);
//查询全部用户信息
public List<User> getAll();
//根据用户名密码进行登录
public User login(String userName,String password);
}
package com.service.impl;
import com.domain.User;
import com.service.UserService;
import java.util.List;
public class UserServiceImpl implements UserService {
@Override
public boolean save(User user) {
return false;
}
@Override
public boolean update(User user) {
return false;
}
@Override
public boolean delete(Integer uuid) {
return false;
}
@Override
public User get(Integer uuid) {
return null;
}
@Override
public List<User> getAll() {
return null;
}
@Override
public User login(String userName, String password) {
return null;
}
}
项目结构已搭建完成
2.spring整合mybatis(part1+part2)
创建Mybatis映射文件
创建Spring配置文件
组件扫描
整合Mybatis到Spring环境正
SQLSessionFactoryBean
数据源(druid+jdbc.properties)
映射扫描
注解事务
分页插件
创建单元测试
package com.dao;
import com.domain.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserDao {
//添加用户
public boolean save(User user);
//修改用户
public boolean update(User user);
//删除用户
public boolean delete(Integer uuid);
//查询单个用户信息
public User get(Integer uuid);
//查询全部用户信息
public List<User> getAll();
//根据用户密码查询用户信息
public User getByUserNameAndPassword(@Param("userName") String userName,@Param("password") String password);
}
package com.service;
import com.domain.User;
import com.github.pagehelper.PageInfo;
import org.springframework.transaction.annotation.Transactional;
@Transactional(readOnly = true)
public interface UserService {
//添加用户
@Transactional(readOnly = false)
public boolean save(User user);
//修改用户
@Transactional(readOnly = false)
public boolean update(User user);
//删除用户
@Transactional(readOnly = false)
public boolean delete(Integer uuid);
//查询单个用户信息
public User get(Integer uuid);
//查询全部用户信息
public PageInfo<User> getAll(int page, int size);
//根据用户名密码进行登录
public User login(String userName,String password);
}
package com.service.impl;
import com.dao.UserDao;
import com.domain.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
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 uuid) {
return userDao.delete(uuid);
}
@Override
public User get(Integer uuid) {
return userDao.get(uuid);
}
@Override
public PageInfo<User> getAll(int page,int size) {
PageHelper.startPage(page,size);
List<User> all =userDao.getAll();
return new PageInfo<User>(all);
}
@Override
public User login(String userName, String password) {
return userDao.getByUserNameAndPassword(userName,password);
}
}
com.dao.UserDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis的DTD约束-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--mapper:核心根标签;namespace属性:名称空间-->
<mapper namespace="com.dao.UserDao">
<!--添加-->
<insert id="save" parameterType="user">
INSERT INTO user(userName,password,realName,gender,birthday) VALUES (#{userName},#{password}, #{realName}, #{gender},#{birthday})
</insert>
<!--修改-->
<update id="update" parameterType="user">
UPDATE user SET userName =#{userName},password=#{password},realName=#{realName},gender=#{gender},birthday=#{birthday} WHERE uuid = #{uuid}
</update>
<!--删除-->
<delete id="delete" parameterType="int">
DELETE FROM user WHERE uuid = ${uuid}
</delete>
<!--查询单个-->
<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>
jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_db?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=123456
applicationContext.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:util="http://www.springframework.org/schema/util"
xmlns:set="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com"/>
<tx:annotation-driven transaction-manager="txManager"/>
<!--加载properties文件-->
<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>
<!--整合mybatis到spring中-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.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.dao"/>
</bean>
<!--事务-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
测试
package com.service;
import com.domain.User;
import com.github.pagehelper.PageInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Date;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testSave(){
User user =new User();
user.setUserName("Jock");
user.setPassword("root");
user.setRealName("Jockme");
user.setGender(1);
user.setBirthday(new Date(3333300000L));
userService.save(user);
}
@Test
public void testDelete(){
User user = new User();
userService.delete(3);
}
@Test
public void testUpdate(){
User user = new User();
user.setUuid(1);
user.setUserName("Jockme");
user.setPassword("root");
user.setRealName("JockIsMe");
user.setGender(1);
user.setBirthday(new Date(3333300000L));
userService.update(user);
}
@Test
public void testGet(){
User user = userService.get(1);
System.out.println(user);
}
@Test
public void testGetAll(){
PageInfo<User> all = userService.getAll(1,2);
System.out.println(all);
System.out.println(all.getList().get(0));
System.out.println(all.getList().get(1));
}
@Test
public void testLogin(){
User user = userService.login("Jockme","root");
System.out.println(user);
}
}
3.SpringMVC(part3)
web.xml加载SpringMVC
rest风格
数据封装为json数据
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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<!--启动服务器时,通过监听器加载spring运行环境-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置过滤器,解析请求中的参数_method,即可通过页面表单提交PUT请求与DELETE请求-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<servlet-name>DispatcherServlet</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>DispatcherServlet</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>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
application.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:util="http://www.springframework.org/schema/util"
xmlns:set="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--开启bean注解扫描-->
<context:component-scan base-package="com">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<tx:annotation-driven transaction-manager="txManager"/>
<!--加载properties文件-->
<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>
<!--整合mybatis到spring中-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.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.dao"/>
</bean>
<!--事务-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
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:util="http://www.springframework.org/schema/util"
xmlns:set="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.controller"/>
<mvc:annotation-driven/>
</beans>
package com.controller;
import com.domain.User;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@PostMapping
public boolean save(User user){
System.out.println("save..."+user);
return true;
}
@PutMapping
public boolean update(User user){
System.out.println("update..."+user);
return true;
}
@DeleteMapping("/{uuid}")
public boolean delete(@PathVariable Integer uuid){
System.out.println("delete..."+uuid);
return true;
}
@GetMapping("/{uuid}")
public User get(@PathVariable Integer uuid){
System.out.println("get..."+uuid);
return null;
}
@GetMapping("/{page}/{size}")
public List getAll(@PathVariable Integer page,@PathVariable Integer size){
System.out.println("getAll..."+page+","+size);
return null;
}
@PostMapping("/login")
public User login(String userName,String password){
System.out.println("login..."+userName+","+password);
return null;
}
}
4.Spring整合SpringMVC与表现层数据封装(part4+prat5-1)
web.xml加载Spring环境
Controller调用Service
package com.controller.results;
public class Result {
//操作结果编码
private Integer code;
//操作数据结构
private Object data;
//消息
private String message;
public Integer getCode() {
return code;
}
public Result(Integer code) {
this.code = code;
}
public Result(Integer code,Object data) {
this.code = code;
this.data = data;
}
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 + '\'' +
'}';
}
}
package com.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;
//系统错误编码
//操作权限编码
//校验结果编码
}
package com.controller;
import com.controller.results.Code;
import com.controller.results.Result;
import com.domain.User;
import com.github.pagehelper.PageInfo;
import com.service.UserService;
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 flag = userService.save(user);
return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERROR);
}
@PutMapping
public Result update(User user){
boolean flag = userService.update(user);
return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERROR);
}
@DeleteMapping("/{uuid}")
public Result delete(@PathVariable Integer uuid){
boolean flag = userService.delete(uuid);
return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERROR);
}
@GetMapping("/{uuid}")
public Result get(@PathVariable Integer uuid){
User user = userService.get(uuid);
return new Result(null != user ?Code.GET_OK:Code.GET_ERROR,user);
}
@GetMapping("/{page}/{size}")
public Result getAll(@PathVariable Integer page, @PathVariable Integer size){
PageInfo<User> all = userService.getAll(page,size);
System.out.println(all.getList().toString());
return new Result(null != all ?Code.GET_OK:Code.GET_ERROR,all);
}
@PostMapping("/login")
public Result login(String userName,String password){
User user = userService.login(userName,password);
return new Result(null != user ?Code.GET_OK:Code.GET_ERROR,user);
}
}
5.问题消息处理(part5-2)
@GetMapping("/{uuid}")
public Result get(@PathVariable Integer uuid){
User user = userService.get(uuid);
if(uuid==10) throw new BusinessException("查询出错,请重试",Code.GET_OK);
return new Result(null != user ?Code.GET_OK:Code.GET_ERROR,user);
}
package com.controller.interceptor;
import com.controller.results.Result;
import com.system.exception.BusinessException;
import org.aspectj.bridge.IMessage;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
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(), e.getMessage());
}
}
package com.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;
//系统错误编码
//操作权限编码
//校验结果编码
}
package com.controller.results;
public class Result {
//操作结果编码
private Integer code;
//操作数据结构
private Object data;
//消息
private String message;
public Integer getCode() {
return code;
}
public Result(Integer code) {
this.code = code;
}
public Result(Integer code,Object data) {
this.code = code;
this.data = data;
}
public Result(Integer code,String message) {
this.code = code;
this.message = message;
}
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 + '\'' +
'}';
}
}
package com.system.exception;
import java.io.PrintStream;
import java.io.PrintWriter;
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;
}
}
package com.system.exception;
import java.io.PrintStream;
import java.io.PrintWriter;
public class SystemException extends RuntimeException{
public SystemException() {
super();
}
public SystemException(String message) {
super(message);
}
public SystemException(String message, Throwable cause) {
super(message, cause);
}
public SystemException(Throwable cause) {
super(cause);
}
protected SystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
@Override
public String getMessage() {
return super.getMessage();
}
@Override
public String getLocalizedMessage() {
return super.getLocalizedMessage();
}
@Override
public synchronized Throwable getCause() {
return super.getCause();
}
@Override
public synchronized Throwable initCause(Throwable cause) {
return super.initCause(cause);
}
@Override
public String toString() {
return super.toString();
}
@Override
public void printStackTrace() {
super.printStackTrace();
}
@Override
public void printStackTrace(PrintStream s) {
super.printStackTrace(s);
}
@Override
public void printStackTrace(PrintWriter s) {
super.printStackTrace(s);
}
@Override
public synchronized Throwable fillInStackTrace() {
return super.fillInStackTrace();
}
@Override
public StackTraceElement[] getStackTrace() {
return super.getStackTrace();
}
@Override
public void setStackTrace(StackTraceElement[] stackTrace) {
super.setStackTrace(stackTrace);
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
@Override
protected void finalize() throws Throwable {
super.finalize();
}
}