欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

全局参数校验

程序员文章站 2022-04-25 20:01:23
...

1 pom.xml引入依赖

<!--参数校验-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2 get请求

/**
 * test
 *
 * @author gaorimao
 * @since 2021-04-29
 */
@RestController
@Validated
public class TestController {
    /**
     * get请求,拼在路径上的参数校验,需要在控制器上添加@Validated注解
     */
    @GetMapping("/test/get/params")
    public Result testUsername(@Length(min = 4) @RequestParam("username") String username,
                               @Length(max = 4) @RequestParam("password") String password) {
        return Result.success();
    }
}

3 POST请求

/**
 * 将校验结果放进BindingResult里面,用户自行判断并处理
 */
@PostMapping(value = "/test/params", produces = "application/json;charset=UTF-8")
public Result testBindingResult(@RequestBody @Valid LoginRequest loginRequest) {
    return Result.success();
}

请求体注解

import lombok.Data;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;


@Data
public class LoginRequest {
    @NotBlank(message = "用户名不能为空!")
    @Min(value = 5)
    private String username;
    @NotBlank(message = "密码不能为空!")
    private String password;
}

4 全局自定义异常捕获

import com.grm.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.StringJoiner;

/**
 * 自定义全局异常捕获
 *
 * @author gaorimao
 */
@RestControllerAdvice(annotations = RestController.class)
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 全局异常捕捉处理
     *
     * @param e 异常
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result errorHandler(HttpServletRequest req, Exception e) {
        return Result.failed(500, e.getMessage());
    }

    /**
     * 全局异常捕捉处理
     *
     * @param e 异常
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public Result businessExceptionHandler(HttpServletRequest req, Exception e) {
        return Result.failed(500, e.getMessage());
    }

    /**
     * post请求body体参数校验,异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("[exception] methodArgumentNotValidException error : {}",e);
        // 将所有的错误提示使用";"拼接起来并返回
        StringJoiner sj = new StringJoiner(";");
        //name:不能为空;password:长度不能小于4
        e.getBindingResult().getFieldErrors().forEach(x -> sj.add(x.getField()+":"+x.getDefaultMessage()));
        return Result.failed(500, sj.toString());
    }

    /**
     * 缺少body请求体异常处理器
     *
     * @param e 缺少请求体异常
     * @return ResponseResult
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) {
        return Result.failed(500, "body请求体不能为空!");
    }

    /**
     * 忽略参数异常处理器
     *
     * @param e 忽略参数异常
     * @return ResponseResult
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result parameterMissingExceptionHandler(MissingServletRequestParameterException e) {
        return Result.failed(500, "请求参数"+e.getParameterName()+"不能为空!");
    }
}

相关标签: # 6 框架 java