springboot 全局请求参数验证aop

阅读数:80 评论数:0

跳转到新版页面

分类

python/Java

正文

一、目标

默认对全局请求参数进行验证,无需加注解@Validated。

二、具体实现

1、定制全局异常处理器GlobalExceptionHandler

/**
 * 全局异常处理
 *
 * @author seer
 * @version 1.0
 * @date 2022/6/9 15:40
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        log.warn("请求方式不支持 {} {}", request.getServletPath(), e.getMethod());
        return Result.fail(e.getMessage());
    }

    /**
     * 参数验证错误
     */
    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException e, HttpServletRequest request) {
        String message = e.getAllErrors().get(0).getDefaultMessage();
        log.warn("请求参数错误 {} {}", request.getServletPath(), message);
        return Result.fail(Result.Type.REQUEST_PARAM_ERROR, message);
    }

    /**
     * 参数绑定异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result handleBindException(MissingServletRequestParameterException e, HttpServletRequest request) {
        String message = e.getMessage();
        log.warn("参数绑定异常 {} {}", request.getServletPath(), message);
        return Result.fail(Result.Type.REQUEST_PARAM_ERROR, e.getParameterName() + " 未提供");
    }

    /**
     * 参数验证错误
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result handleBindException(ConstraintViolationException e, HttpServletRequest request) {
        String message = e.getMessage();
        log.warn("参数验证错误 {} {}", request.getServletPath(), message);
        return Result.fail(Result.Type.REQUEST_PARAM_ERROR, e.getMessage());
    }
}

2、自定义aop GlobalValidAspect

(1)抛出ConstraintViolationException异常

package com.sdhs.wash.admin.component;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

/**
 * 请求参数验证
 * 基本数据类型,由@RequestParam注解,走框架
 * 对象由此校验,不区分是否添加 @RequestBody
 *
 * @author seer
 * @date 2022-06-28 22:06:04
 */
@Aspect
@Component
@Slf4j
public class GlobalValidAspect {

    @Autowired
    private SpringValidatorAdapter validator;

    /**
     * 前置
     *
     * @param joinPoint joinPoint
     */
    @Before("execution(public * com.sdhs.oilcoreserver.admin.controller.*.*(..))")
    public void atBefore(JoinPoint joinPoint) {
        for (Object arg : joinPoint.getArgs()) {
            Set<ConstraintViolation<Object>> violationSet = validator.validate(arg);
            if (!violationSet.isEmpty()) {
                throw new ConstraintViolationException(violationSet.iterator().next().getMessage(), null);
            }
            return;
        }
    }
}

 




相关推荐

一、概述 springboot中有两种方式使用kafka时,直接使用kafka-client连接kafka服务;另一种是使用spring-kafka框架来连接kafka。 1、版本兼容 使用时要注意版

当然可以自己写redis的工具类,或者使用第三方开源jar包或代码,这里使用spring boot的集成类。 一、pom依赖 <dependency> <gro

websocket协议基于tcp的网络协议,它实现浏览器与器全双工通信。 spring boot2 +websocket 1、添加依赖 <pre clas

背景: 之前用spring boot+mybatis+oracle,现在要改成spring boot_mybatis+postgresql。 为了想让一套代码即可

共同点 都是用来表示Spring某个类是否可以接收HTTP请求。 不同点 @Controller标识一个spring类是Spring MVC c

系统异常捕获 参见:spring boot 2 全局异常处理 @ControllerAdvice(annotations = {RestController.class}) public class

从SSH(Structs/Spring/Hibernate)到SSM(SpringMVC/Spring/MyBatis),到现在一个S(Spring)就够的年代,可见Spring越来越重要了。<

@ConditionalOnMissingBean只能在@Bean注解的方法上使用。 可以给该注解传入参数例如@ConditionOnMissingBean(name = "exa

一、自定义注解 使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。在定义注解时,不能继承其他的注解或接口。

一、Spring的AOP Spring的AOP本质是一种动态代理,常用于权限控制、缓存、日志处理、事务控制等,实现中使用JDK动态代理(接口)和CGLAB动态代理(子类)。 二、AOP的常用术语 1、