灵活使用AOP面向切面Aspect校验Controller层单个类型的参数是否为空

本文主要是介绍灵活使用AOP面向切面Aspect校验Controller层单个类型的参数是否为空,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

我们经常注解使用对controller传过来的参数进行判空校验,但使用注解校验的话常常会遇到controller层方法接收的必须是一个对象(实体类),而我们要校验并使用的值只有一个或几个,这样就会导致判空会出现校验不灵活的问题,只适合表单提交校验比较合适,但对一个参数或几个参数字段校验就不行了。那么我们可以使用AOP机制完美解决cotroller层中参数进行校验问题。


1.在springmvc.xml配置文件中扫描aop存放aspect的相关类 

<context:component-scan base-package="com.awaymeet.fly.platform.aspect"/>
<!--启动AspectJ支持-->
<aop:aspectj-autoproxy proxy-target-class="true" />

2.创建aspect包和VerificationAspect.java类(用于拦截参数校验)

package com.awaymeet.fly.platform.aspect;import com.awaymeet.fly.platform.exception.bean.Nullable;
import com.awaymeet.fly.platform.exception.bean.ParameterException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;/*** 处理数据校验,配合 自定义注解* 默认所有参数为空,若可以为空则在 参数前 加注解,其他校验未写*/@Aspect
@Component
public class VerificationAspect {/*** 声明切面 应用在,所有 Controller下的, 以Controller结尾的类中的,所有 public 方法*/@Pointcut("execution(public * com.awaymeet.fly.platform.controller.*.*(..))")public void joinPointInAllController() {}/*** 切入点执行前方法** @param point 切入点*/@Before("joinPointInAllController()")public void checkParameter( JoinPoint point) throws Exception {String[] paramNames = ((CodeSignature) point.getSignature()).getParameterNames(); //keyObject[] args = point.getArgs();//value// 获得切入的方法Method method = ((MethodSignature) point.getSignature()).getMethod();// 获得所有参数Parameter[] parameters = method.getParameters();// 保存需要校验的argsMap<Object,Object> map = new HashMap<Object,Object>();// 对没有Nullable注解的参数进行非空校验for (int i = 0; i < parameters.length; i++) {Parameter parameter = parameters[i];String name = parameter.getName();Annotation[] annotations = parameter.getDeclaredAnnotationsByType(Nullable.class);if (annotations.length < 1) {if(StringUtils.isEmpty(args[i])){map.put(paramNames[i],"");}else{map.put(paramNames[i],args[i]);}}}for (Object o : map.keySet()) {if (StringUtils.isEmpty(map.get(o))) {String name = "" ;if(o instanceof  String){name = (String)o ;}else{name = o.getClass().getName();}//字段名+参数为空!throw new ParameterException(name +"参数为空!");}}}
}

自定义异常类ParameterException。如果遍历的参数为空则抛出自定义异常,抛出的异常统一在@ControllerAdvice注解类进行异常捕捉。

3.自定义参数可以为空的注解Nullable.java(在controller层的参数前添加该注解表示:该参数可为空)

package com.awaymeet.fly.platform.exception.bean;import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.PARAMETER;
/*** 数据校验 | 可空* 加在 Controller 的函数 的 参数 前面,本注解代表可空, 其他未写*/@Retention(RetentionPolicy.RUNTIME)
@Target({PARAMETER})
public @interface Nullable {}

自定义异常类ParameterException.java

package com.awaymeet.fly.platform.exception.bean;public class ParameterException extends Exception {public ParameterException(Exception e)  {super(e);}public ParameterException(String message)  {super(message);}
}

4.使用@ControllerAdvice注解创建统一异常处理类GlobalExceptionHandler.java

package com.awaymeet.fly.platform.exception;import com.awaymeet.fly.common.pojo.APPFinalConfig;
import com.awaymeet.fly.common.pojo.JResult;
import com.awaymeet.fly.common.utils.JsonUtils;
import com.awaymeet.fly.platform.exception.bean.InternalAPIServiceException;
import com.awaymeet.fly.platform.exception.bean.UserException;
import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.lang.reflect.UndeclaredThrowableException;/*** @Title: exceptionHandle* @Description: 默认异常处理* @author lc* @param ex* @return JResult    返回类型*/@ExceptionHandler(Exception.class)@ResponseBodypublic JResult  exceptionHandle( Exception ex)throws IOException {log.error(APPFinalConfig.ERROR, ex);JResult result = new JResult();result.setErrorCode(APPFinalConfig.ERROR);result.setState("-1001");result.setDescription("系统出现异常");return result ;}/*** @Description: 对象参数异常处理* @author lc* @param ex* @throws* @return JResult    返回类型*/@ExceptionHandler(BindException.class)@ResponseBodypublic JResult  bindException(BindException ex) {log.error(APPFinalConfig.ERROR, ex);JResult result = new JResult();result.setErrorCode(APPFinalConfig.ERROR);result.setState("-1001");StringBuilder msg = new StringBuilder() ;BindException exception = (BindException)ex ;for (FieldError error : exception.getBindingResult().getFieldErrors()) {/*msg.append("参数");msg.append(error.getField());msg.append("=");msg.append(error.getRejectedValue());msg.append(",说明:");*/msg.append(error.getDefaultMessage());}result.setDescription(msg.toString());return result ;}/*** @Title: exceptionHandle* @Description: 单个或几个参数异常处理* @author lc* @param ex* @throws IOException* @return JResult    返回类型*/@ExceptionHandler(UndeclaredThrowableException.class)@ResponseBodypublic JResult  parameterException(UndeclaredThrowableException ex)throws IOException {log.error(APPFinalConfig.ERROR, ex);JResult result = new JResult();result.setErrorCode(APPFinalConfig.ERROR);result.setState("-1001");result.setDescription(ex.getCause().getMessage());return result ;}
}

5.controller层请求的相应方法体

@RequestMapping("/select")@ResponseBodypublic JResult select(long id ,String inspectionName ){return auditAndRagistService.select(id);}

最后运行项目,发送请求!

这篇关于灵活使用AOP面向切面Aspect校验Controller层单个类型的参数是否为空的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/805604

相关文章

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Java使用jar命令配置服务器端口的完整指南

《Java使用jar命令配置服务器端口的完整指南》本文将详细介绍如何使用java-jar命令启动应用,并重点讲解如何配置服务器端口,同时提供一个实用的Web工具来简化这一过程,希望对大家有所帮助... 目录1. Java Jar文件简介1.1 什么是Jar文件1.2 创建可执行Jar文件2. 使用java

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

Java中的抽象类与abstract 关键字使用详解

《Java中的抽象类与abstract关键字使用详解》:本文主要介绍Java中的抽象类与abstract关键字使用详解,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧... 目录一、抽象类的概念二、使用 abstract2.1 修饰类 => 抽象类2.2 修饰方法 => 抽象方法,没有

MyBatis ParameterHandler的具体使用

《MyBatisParameterHandler的具体使用》本文主要介绍了MyBatisParameterHandler的具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参... 目录一、概述二、源码1 关键属性2.setParameters3.TypeHandler1.TypeHa

Spring 中的切面与事务结合使用完整示例

《Spring中的切面与事务结合使用完整示例》本文给大家介绍Spring中的切面与事务结合使用完整示例,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录 一、前置知识:Spring AOP 与 事务的关系 事务本质上就是一个“切面”二、核心组件三、完