SpringBoot实战篇之接口参数校验和全局异常处理

119 阅读2分钟

前言 对接口请求参数校验是每一个开发人员都必须熟知且善用的功能,是保证程序健壮性的基石。

除引入方式不同,使用方式和SpringMvc基本一致。

一、参数校验

  1. 引入库 org.springframework.boot spring-boot-starter-validation
  1. 全局异常处理 package org.example.springboot3.config;

import jakarta.validation.ConstraintViolationException; import org.example.springboot3.bigevent.entity.Result; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice;

/**

  • Create by sean on 2024/6/14 */ @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ConstraintViolationException.class) public Result exceptionHadler(ConstraintViolationException ex){ return error(ex); } @ExceptionHandler(Exception.class) public Result exceptionHadler(Exception ex){ return error(ex); } private Result error(Exception ex){ return Result.error(StringUtils.hasLength(ex.getMessage())?ex.getMessage():"操作失败"); } }
  1. 控制器类 package org.example.springboot3.bigevent.controller;

import jakarta.validation.constraints.Pattern; import org.example.springboot3.bigevent.entity.Result; import org.example.springboot3.bigevent.entity.User; import org.example.springboot3.bigevent.service.UserSerivce; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;

/**

  • Create by sean on 2024/6/14 */ @RequestMapping("/user/") @RestController @Validated public class UserController1 { @Autowired UserSerivce userSerivce; @RequestMapping("register") public Result register(@Pattern(regexp = "^\S{6,20}",message = "用户名长度为6-20位") String username,@Pattern(regexp = "^\\S{8,20}",message = "密码为8-20位") String password){ User user=userSerivce.findUserByName(username); if(user==null){//用户不存在,可以注册 int i=userSerivce.addUser(username,password); if(i!=1){ return Result.error("失败注册,请稍后重新注册!"); } }else{ return Result.error("该用户已存在,请重新注册!"); } return Result.success(); } }
  1. 响应 {"code":1,"message":"register.username: 用户名长度为6-20位, register.password: 密码为8-20位","data":null} 1 二、对象校验 上面只有两个参数,我们可以直接校验,但是参数过多的时候我们都会直接使用对象校验。

1.实体类 校验写在实体类对象对应属性上

package org.example.springboot3.bigevent.entity;

import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import jakarta.validation.constraints.Pattern; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.time.LocalDateTime;

@Getter @Setter @ToString public class User { @TableId(type=IdType.AUTO) private Integer id;//主键ID @Pattern(regexp = "^\S{6,20}",message = "用户名长度为6-20位") private String username;//用户名 @Pattern(regexp = "^\\S{8,20}",message = "密码为8-20位") private String password;//密码 private String nickname;//昵称 private String email;//邮箱 private String userPic;//用户头像地址 private LocalDateTime createTime;//创建时间 private LocalDateTime updateTime;//更新时间 }

2.控制器类 package org.example.springboot3.bigevent.controller;

import jakarta.validation.Valid; import jakarta.validation.constraints.Pattern; import org.example.springboot3.bigevent.entity.Result; import org.example.springboot3.bigevent.entity.User; import org.example.springboot3.bigevent.service.UserSerivce; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;

/**

  • Create by sean on 2024/6/14 */ @RequestMapping("/user/") @RestController @Validated public class UserController1 { @Autowired UserSerivce userSerivce; @RequestMapping("register1") public Result register1(@Valid User user){ if(userSerivce.findUserByName(user.getUsername())==null){//用户不存在,可以注册 int i=userSerivce.addUser(user.getUsername(),user.getPassword()); if(i!=1){ return Result.error("失败注册,请稍后重新注册!"); } }else{ return Result.error("该用户已存在,请重新注册!"); } return Result.success(); } }
  1. 全局异常处理 对象数据校验信息太繁琐,我们简化到关键信息

package org.example.springboot3.config;

import jakarta.validation.ConstraintViolationException; import org.example.springboot3.bigevent.entity.Result; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.stream.Collectors;

/**

  • Create by sean on 2024/6/14 */ @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public Result exceptionHadler(MethodArgumentNotValidException ex){//对象数据校验信息太繁琐,我们简化到关键信息 BindingResult bindingResult = ex.getBindingResult(); if(bindingResult.hasFieldErrors()){ String message = bindingResult.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(";")); return error(message); } return error(ex); } @ExceptionHandler(Exception.class) public Result exceptionHadler(Exception ex){ return error(ex); } private Result error(String message){ return Result.error(message); } private Result error(Exception ex){ return Result.error(StringUtils.hasLength(ex.getMessage())?ex.getMessage():"操作失败"); } }
  1. 响应 {"code":1,"message":"用户名长度为6-20位;密码为8-20位","data":null}