【第2章】SpringBoot实战篇之接口参数校验和全局异常处理


前言

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

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


一、参数校验

1. 引入库

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2. 全局异常处理

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 zjg on 2024/5/23
 */
@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():"操作失败");
    }
}

3. 控制器类

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 zjg on 2024/5/22
 */
@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();
    }
}

4. 响应

{"code":1,"message":"register.username: 用户名长度为6-20位, register.password: 密码为8-20位","data":null}

二、对象校验

上面只有两个参数,我们可以直接校验,但是参数过多的时候我们都会直接使用对象校验。

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 zjg on 2024/5/22
 */
@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();
    }
}

3. 全局异常处理

对象数据校验信息太繁琐,我们简化到关键信息

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 zjg on 2024/5/23
 */
@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():"操作失败");
    }
}

4. 响应

{"code":1,"message":"用户名长度为6-20位;密码为8-20位","data":null}

总结

回到顶部

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值