springboot对全局异常进行封装以及向前端传JSON数据

springboot对全局异常进行封装以及向前端传JSON数据,第1张

对全局异常的封装以及JSON数据的传递

我们在使用前后端交互时都会出现大大小小的异常,在springboot里面提供一个@ExceptionHandler全局异常注解,
以及这次就如何将一些信息传递给前端进行数据接受
前端就是要Jquery进行获取JSON数据,需要将jquery导入静态资源文件中

sql语句
/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 50045
 Source Host           : localhost:3306
 Source Schema         : store

 Target Server Type    : MySQL
 Target Server Version : 50045
 File Encoding         : 65001

 Date: 24/04/2022 10:15:37
*/

SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
  `uid` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户id',
  `username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '用户名',
  `password` char(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '密码',
  `salt` char(36) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '盐值',
  `phone` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '电话号码',
  `email` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '电子邮箱',
  `gender` int(11) NULL DEFAULT NULL COMMENT '性别:0-女,1-男',
  `avatar` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '头像',
  `is_delete` int(11) NULL DEFAULT 0 COMMENT '是否删除:0-未删除,1-已删除',
  `created_user` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '日志-创建人',
  `created_time` datetime NULL DEFAULT NULL COMMENT '日志-创建时间',
  `modified_user` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '日志-最后修改执行人',
  `modified_time` datetime NULL DEFAULT NULL COMMENT '日志-最后修改时间',
  PRIMARY KEY USING BTREE (`uid`),
  UNIQUE INDEX `username` USING BTREE(`username`)
) ENGINE = InnoDB AUTO_INCREMENT = 12 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES (1, 'xuda', '654321', NULL, '17858802222', 'admin@cy.com', 1, NULL, 0, NULL, NULL, '系统管理员', '2022-03-25 20:40:47');
INSERT INTO `t_user` VALUES (2, 'xu', '123456', NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL);
INSERT INTO `t_user` VALUES (3, 'xudada', 'A3FDC69BC233E052FED8384450F8C916', '54656473-D42F-4F5C-AF58-EDBACD985F5F', NULL, NULL, NULL, NULL, 0, 'xu', '2022-03-26 09:35:10', 'xu', '2022-03-26 09:35:10');
INSERT INTO `t_user` VALUES (4, 'liu', '2C0EEB23FA69F59913FF6AF0413544DE', 'AFA0A835-B0B8-468B-8FC5-21A795BC3D41', '123456789123', '123456@qq.com', 0, NULL, 0, 'liu', '2022-03-26 09:36:09', 'liu', '2022-03-26 14:11:30');
INSERT INTO `t_user` VALUES (5, 'test003', '224EF0683DD578324F7A3E16FBA87B7A', '44D8FCFC-FBF2-41BF-8A2F-79BFE6BFE4C5', '1234568989', '123@qq.com', 0, '1', 0, 'test003', '2022-03-26 10:09:38', 'test003', '2022-04-01 15:07:01');
INSERT INTO `t_user` VALUES (7, 'root', 'F028763BD22DF7083DB3DA3A67E2A5B8', '9C5A3B46-89DB-4A76-BF2E-5AF1C673B175', NULL, NULL, NULL, NULL, 0, 'root', '2022-03-26 18:16:30', 'root', '2022-03-26 18:16:30');
INSERT INTO `t_user` VALUES (8, 'xu', 'CDAF24460CEF01C63A63A4E53E3C62EC', '6334CD55-97CC-427C-8B56-3B461F1821F5', NULL, NULL, NULL, NULL, 0, 'xu', '2022-04-23 15:50:50', 'xu', '2022-04-23 15:50:50');
INSERT INTO `t_user` VALUES (9, 'root1', '3437DB35E405184265C500607AC171C4', '63CB0515-2F21-4A10-A46F-15419CBEFFC7', '1763096', '137559@qq.com', 1, NULL, 0, 'root1', '2022-04-23 15:51:44', 'root1', '2022-04-23 15:54:32');
INSERT INTO `t_user` VALUES (10, 'li', '93D2AF9CDBD3AF2A5E0E358EA678EF51', 'ADF3619E-0BC4-43E3-AE85-0DDFB31EA157', NULL, NULL, NULL, NULL, 0, 'li', '2022-04-23 16:07:09', 'li', '2022-04-23 16:07:09');
INSERT INTO `t_user` VALUES (11, 'spy', 'ACA7B86FA72A3346BCFB64999AF31DBE', 'A5715388-CC41-45CB-BCEB-E196272E4AE5', NULL, NULL, NULL, NULL, 0, 'spy', '2022-04-23 16:09:02', 'spy', '2022-04-23 16:09:02');

SET FOREIGN_KEY_CHECKS = 1;

pom

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.6.7version>
        <relativePath/> 
    parent>
    <groupId>com.xuda.practicegroupId>
    <artifactId>exceptinotherartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>exceptinothername>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>com.baomidougroupId>
            <artifactId>mybatis-plus-boot-starterartifactId>
            <version>3.5.1version>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjtoolsartifactId>
        dependency>
        <dependency>
            
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombokgroupId>
                            <artifactId>lombokartifactId>
                        exclude>
                    excludes>
                configuration>
            plugin>
        plugins>
    build>

project>

1.实体类
package com.xuda.practice.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-24 10:09
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("t_user")
public class User extends BaseEntity implements Serializable {
    @TableId
    private Long uid;
    private String username;
    private String password;
    private String salt;
    private String phone;
    private String email;
    private Integer gender;
    private String avatar;
    @TableLogic //逻辑删除
    private Integer isDelete;
}

配置

我使用的mysql8

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/chat?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false

    password: 123456
    username: root
#服务器向客户端不响应为null的属性
  jackson:
    default-property-inclusion: non_null
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      table-prefix: t_
      id-type: auto
2.公共父类
package com.xuda.practice.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Date;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-24 10:17
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BaseEntity {
    private String createdUser;
    private Date createdTime;
    private String modifiedUser;
    private Date modifiedTime;
}

3.mapper类
package com.xuda.practice.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xuda.practice.entity.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper extends BaseMapper<User> {
}

4.service类
package com.xuda.practice.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.xuda.practice.entity.User;
import org.springframework.stereotype.Service;


public interface UserService extends IService<User> {
    /**
     * 用户注册
     * @param user 用户数据
     */
    void reg(User user);

    void contextLoads();
}

5.service实现类
package com.xuda.practice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuda.practice.entity.User;
import com.xuda.practice.mapper.UserMapper;
import com.xuda.practice.service.UserService;
import com.xuda.practice.service.ex.InsertException;
import com.xuda.practice.service.ex.UsernameDuplicateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-24 10:10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void reg(User user) {
        //更具参数user对象获取注册的用户名
        String username = user.getUsername();
        System.out.println(username);
        //调用持久层查询username查用户数据
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        /**
         * 下面使用的是userMapper.selectOne(queryWrapper);这里查询的结果为null
         * 如果将user1的结果取username去判断,这里会报空指针异常,因为这是在使用userMapper.selectOne(queryWrapper)进行查询的对象是null
         * 而他的值是取不到的,所以就只能去进行对象的判断是否为空
         */
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 != null) {
            throw new UsernameDuplicateException("用户名被占用[" + user1.getUsername() + "]");
        }
            Date date = new Date();
            String salt = UUID.randomUUID().toString().toUpperCase(); //盐值
            String md5Password = getMd5Password(user.getPassword(), salt);
            user.setPassword(md5Password);
            user.setSalt(salt);
            user.setCreatedUser(username);
            user.setCreatedTime(date);
            user.setModifiedUser(username);
            user.setModifiedTime(date);
            int insert = userMapper.insert(user);
            if (insert != 1) {
                throw new InsertException("添加账户信息产生未知异常,请从新输入");
        }
    }

    /**
     * 进行测试插入数据
     */
    public void contextLoads() {
        User user = new User();
        user.setUsername("test007");
        user.setPassword("123456");
        //加密
        String salt = UUID.randomUUID().toString().toUpperCase(); //盐值
        String md5Password = getMd5Password(user.getPassword(), salt);
        user.setPassword(md5Password);
        user.setSalt(salt);
        user.setCreatedUser(user.getUsername());
        user.setModifiedTime(new Date());
        user.setModifiedUser(user.getUsername());
        user.setCreatedTime(new Date());

        //进行插入
        int insert = userMapper.insert(user);
        System.out.println(insert);
    }

    /**
     * 执行密码加密
     * @param password 原始密码
     * @param salt 盐值
     * @return 加密后的密文
     */
    private String getMd5Password(String password, String salt) {
        /**
         * 加密规则
         * 1.无视原始密码强度
         * 2. 使用UUID作为盐值,在原始密码的左右两侧拼接
         * 3.循环加密3次
         */
        for (int i = 0; i < 3; i++) {
            password = DigestUtils.md5DigestAsHex((salt + password + salt).getBytes()).toUpperCase();
        }
        return password;
    }
}

6.service插入异常类
package com.xuda.practice.service.ex;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-24 10:50
 */
public class InsertException extends ServiceException{
    public InsertException() {
        super();
    }

    public InsertException(String message) {
        super(message);
    }

    public InsertException(String message, Throwable cause) {
        super(message, cause);
    }

    public InsertException(Throwable cause) {
        super(cause);
    }

    protected InsertException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

7.service异常类
package com.xuda.practice.service.ex;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-24 10:50
 */
public class ServiceException extends RuntimeException{
    public ServiceException() {
        super();
    }

    public ServiceException(String message) {
        super(message);
    }

    public ServiceException(String message, Throwable cause) {
        super(message, cause);
    }

    public ServiceException(Throwable cause) {
        super(cause);
    }

    protected ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

8.service名称被占用异常
package com.xuda.practice.service.ex;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-24 11:10
 */
public class UsernameDuplicateException extends ServiceException{
    public UsernameDuplicateException() {
        super();
    }

    public UsernameDuplicateException(String message) {
        super(message);
    }

    public UsernameDuplicateException(String message, Throwable cause) {
        super(message, cause);
    }

    public UsernameDuplicateException(Throwable cause) {
        super(cause);
    }

    protected UsernameDuplicateException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

9.controller类
package com.xuda.practice.controller;

import com.xuda.practice.entity.BaseEntity;
import com.xuda.practice.entity.User;
import com.xuda.practice.service.UserService;
import com.xuda.practice.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-24 10:46
 */
@RestController
@RequestMapping("user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @RequestMapping(value = "reg")
    public JsonResult<Void> reg(User user) {
        //调用业务对象进行注册
        System.out.println(user);
        userService.reg(user);
        return new JsonResult<Void>(OK);
    }
    @RequestMapping(value = "login1")
    public JsonResult<Void> contextLoads() {
        //调用业务对象进行注册
        userService.contextLoads();
        return new JsonResult<Void>(OK);
    }

}

10.controller 全局捕获异常类
package com.xuda.practice.controller;

/**
 * @author :程序员徐大大
 * @description:统一处理异常
 * @date :2022-04-24 10:46
 */

import com.xuda.practice.service.ex.InsertException;
import com.xuda.practice.service.ex.ServiceException;
import com.xuda.practice.utils.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/** 控制器基类 */
public class BaseController {
    /**  *** 作成功的状态码 */
    public static final int OK = 200;

    /**
     * 从HttpSession对象中获取uid
     * @param session HttpSession对象
     * @return 当前登录的用户的id
     */
    private final Integer getUidFromSession(HttpSession session) {
        return Integer.valueOf(session.getAttribute("uid").toString());
    }

    /**
     * 从HttpSession对象中获取用户名
     * @param session HttpSession对象
     * @return 当前登录的用户名
     */
    protected final String getUsernameFormSession(HttpSession session) {
        return session.getAttribute("username").toString();
    }
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e) {
        JsonResult<Void> result = new JsonResult<Void>(e);
        if (e instanceof InsertException) {
            result.setState(4000);
        }
        return result;
    }
}

11.JSON工具类
package com.xuda.practice.utils;

import java.io.Serializable;

/**
 * @author :程序员徐大大
 * @description:返回前端字符串
 * @date :2022-04-24 10:46
 */
public class JsonResult<E> implements Serializable {
    /** 状态码 */
    private Integer state;
    /** 状态描述信息 */
    private String message;
    /** 数据 */
    private E data;

    public JsonResult() {
        super();
    }

    public JsonResult(Integer state) {
        super();
        this.state = state;
    }

    /** 出现异常时调用 */
    public JsonResult(Throwable e) {
        super();
        // 获取异常对象中的异常信息
        this.message = e.getMessage();
    }

    public JsonResult(Integer state, E data) {
        super();
        this.state = state;
        this.data = data;
    }

    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public E getData() {
        return data;
    }

    public void setData(E data) {
        this.data = data;
    }
}

12.拦截器控制(与本次主题无关)
package com.xuda.practice.config;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-24 13:39
 */

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** 定义处理器拦截器 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getSession().getAttribute("uid") != null) {
            response.sendRedirect("/web/index.html");
            return true;
        }
        return true;
    }
}

package com.xuda.practice.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :程序员徐大大
 * @description:TODO
 * @date :2022-04-24 13:38
 */
@Configuration
public class LoginInterceptorConfigurer implements WebMvcConfigurer {
    /** 拦截器配置 */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 创建拦截器对象
        HandlerInterceptor interceptor = new LoginInterceptor();

        // 白名单
        List<String> patterns = new ArrayList<String>();
        patterns.add("/bootstrap3/**");
        patterns.add("/css/**");
        patterns.add("/images/**");
        patterns.add("/js/**");
        patterns.add("/web/register.html");
        patterns.add("/web/login.html");
        patterns.add("/web/index.html");
        patterns.add("/web/product.html");
        patterns.add("/user/reg");
        patterns.add("/user/login");
        patterns.add("/districts/**");
        patterns.add("/products/**");

        // 通过注册工具添加拦截器
        registry.addInterceptor(interceptor).addPathPatterns("/**").excludePathPatterns(patterns);
    }
}
13.前端获取JSON数据
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../bootstrap3/js/holder.js"></script>
    <link href="../bootstrap3/css/bootstrap.css" rel="stylesheet" type="text/css">
    <script src="../bootstrap3/jquery-1.9.1.min.js"></script>
    <script src="../bootstrap3/js/bootstrap.js"></script>

   </head>
<body>
<p>注册页面</p>
    <form id="form-login" action="index.html" method="post">
        <input type="text" name="username" class="form-control" id="username" placeholder="请输入用户名">
        <input type="password" class="form-control" id="password" name="password" placeholder="请输入密码">
        <input id="btn-login" class="btn btn-primary" type="button" value="登录" />
    </form>

<script type="text/javascript">
    $("#btn-login").click(function () {
        $.ajax({
            url: "/user/reg",
            type: "POST",
            data: $("#form-login").serialize(),
            dataType: "json",
            success: function (json) {
                if (json.state == 200) {
                    alert("注册成功");
                    location.href = "register.html";
                } else {
                    alert("注册失败"+json.message);
                }
            }
        });
    });
</script>
</body>
</html>
创建springboot工程


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/736451.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存