详解使用Spring AOP和自定义注解进行参数检查
作者:liaosilzu2007 发布时间:2021-11-27 00:06:49
标签:Spring,AOP,注解
引言
使用SpringMVC作为Controller层进行Web开发时,经常会需要对Controller中的方法进行参数检查。本来SpringMVC自带@Valid和@Validated两个注解可用来检查参数,但只能检查参数是bean的情况,对于参数是String或者Long类型的就不适用了,而且有时候这两个注解又突然失效了(没有仔细去调查过原因),对此,可以利用Spring的AOP和自定义注解,自己写一个参数校验的功能。
代码示例
注意:本节代码只是一个演示,给出一个可行的思路,并非完整的解决方案。
本项目是一个简单Web项目,使用到了:Spring、SpringMVC、Maven、JDK1.8
项目结构:
自定义注解:
ValidParam.java:
package com.lzumetal.ssm.paramcheck.annotation;
import java.lang.annotation.*;
/**
* 标注在参数bean上,表示需要对该参数校验
*/
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValidParam {
}
NotNull.java:
package com.lzumetal.ssm.paramcheck.annotation;
import java.lang.annotation.*;
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NotNull {
String msg() default "字段不能为空";
}
NotEmpty.java:
package com.lzumetal.ssm.paramcheck.annotation;
import java.lang.annotation.*;
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NotEmpty {
String msg() default "字段不能为空";
}
切面类
ParamCheckAspect.java:
package com.lzumetal.ssm.paramcheck.aspect;
import com.lzumetal.ssm.paramcheck.annotation.NotEmpty;
import com.lzumetal.ssm.paramcheck.annotation.NotNull;
import com.lzumetal.ssm.paramcheck.annotation.ValidParam;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.util.Arrays;
/**
* 参数检查切面类
*/
@Aspect
@Component
public class ParamCheckAspect {
@Before("execution(* com.lzumetal.ssm.paramcheck.controller.*.*(..))")
public void paramCheck(JoinPoint joinPoint) throws Exception {
//获取参数对象
Object[] args = joinPoint.getArgs();
//获取方法参数
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Parameter[] parameters = signature.getMethod().getParameters();
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
//Java自带基本类型的参数(例如Integer、String)的处理方式
if (isPrimite(parameter.getType())) {
NotNull notNull = parameter.getAnnotation(NotNull.class);
if (notNull != null && args[i] == null) {
throw new RuntimeException(parameter.toString() + notNull.msg());
}
//TODO
continue;
}
/*
* 没有标注@ValidParam注解,或者是HttpServletRequest、HttpServletResponse、HttpSession时,都不做处理
*/
if (parameter.getType().isAssignableFrom(HttpServletRequest.class) || parameter.getType().isAssignableFrom(HttpSession.class) ||
parameter.getType().isAssignableFrom(HttpServletResponse.class) || parameter.getAnnotation(ValidParam.class) == null) {
continue;
}
Class<?> paramClazz = parameter.getType();
//获取类型所对应的参数对象,实际项目中Controller中的接口不会传两个相同的自定义类型的参数,所以此处直接使用findFirst()
Object arg = Arrays.stream(args).filter(ar -> paramClazz.isAssignableFrom(ar.getClass())).findFirst().get();
//得到参数的所有成员变量
Field[] declaredFields = paramClazz.getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
//校验标有@NotNull注解的字段
NotNull notNull = field.getAnnotation(NotNull.class);
if (notNull != null) {
Object fieldValue = field.get(arg);
if (fieldValue == null) {
throw new RuntimeException(field.getName() + notNull.msg());
}
}
//校验标有@NotEmpty注解的字段,NotEmpty只用在String类型上
NotEmpty notEmpty = field.getAnnotation(NotEmpty.class);
if (notEmpty != null) {
if (!String.class.isAssignableFrom(field.getType())) {
throw new RuntimeException("NotEmpty Annotation using in a wrong field class");
}
String fieldStr = (String) field.get(arg);
if (StringUtils.isBlank(fieldStr)) {
throw new RuntimeException(field.getName() + notEmpty.msg());
}
}
}
}
}
/**
* 判断是否为基本类型:包括String
* @param clazz clazz
* @return true:是; false:不是
*/
private boolean isPrimite(Class<?> clazz){
return clazz.isPrimitive() || clazz == String.class;
}
}
参数JavaBean
StudentParam.java:
package com.lzumetal.ssm.paramcheck.requestParam;
import com.lzumetal.ssm.paramcheck.annotation.NotEmpty;
import com.lzumetal.ssm.paramcheck.annotation.NotNull;
public class StudentParam {
@NotNull
private Integer id;
private Integer age;
@NotEmpty
private String name;
//get、set方法省略...
}
验证参数校验的Controller
TestController.java:
package com.lzumetal.ssm.paramcheck.controller;
import com.google.gson.Gson;
import com.lzumetal.ssm.paramcheck.annotation.NotNull;
import com.lzumetal.ssm.paramcheck.annotation.ValidParam;
import com.lzumetal.ssm.paramcheck.requestParam.StudentParam;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class TestController {
private static Gson gson = new Gson();
@ResponseBody
@RequestMapping(value = "/test", method = RequestMethod.POST)
public StudentParam checkParam(@ValidParam StudentParam param, @NotNull Integer limit) {
System.out.println(gson.toJson(param));
System.out.println(limit);
return param;
}
}
本节示例代码已上传至GitHub:https://github.com/liaosilzu2007/ssm-parent.git
来源:https://segmentfault.com/a/1190000014454607
0
投稿
猜你喜欢
- 在application.properties中填写中文信息,在读取该文件时会出现中文乱码问题。比如:application.propert
- 前言属于基础的面试问题,一定要能够回答全哦~一、继承Thread,重写run方法通过自定义一个类(这里起名为:MyThread),继承Thr
- 常量池中各数据项类型详解常量池中的数据项是通过索引来引用的, 常量池中的各个数据项之间也会相互引用。在这11中常量池数据项类型中, 有两种比
- 帧率(Frame rate)是用于测量显示帧数的量度。所谓的测量单位为每秒显示帧数(Frames per Second,简称:FPS)或“赫
- Spring Boot文件上传与下载在实际的Web应用开发中,为了成功上传文件,必须将表单的method设置为post,并将enctype设
- 今天有个项目需要使用redis,并且有使用脚本的需求。但是因为之前没有写过,所以还有一点点不熟悉,今天记录一下。原因:原子操作,redis会
- 在需要线程同步的时候如何选择合适的线程锁?例:选择可以存入到常量池当中的对象,String对象等public class SyncTest{
- 前言前阵子有同学反馈Flutter中的http请求无法通过fiddler抓包,作者喜欢使用Charles抓包工具,于是抽时间写了个小demo
- 一、前言虽然jdk1.9版本已经问世,但是许多其他的配套设施并不一定支持jdk1.9版本,所以这里仅带领你配置jdk1.8。而jdk1.9的
- 引言你在服务端的安全管理使用了 Spring Security,用户登录成功之后,Spring Security 帮你把用户信息保存在 Se
- JMMJMM是指Java内存模型,不是Java内存布局,不是所谓的栈、堆、方法区。每个Java线程都有自己的工作内存。操作数据,首先从主内存
- 这篇文章主要介绍了基于Java检查IPv6地址的合法性,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋
- 本文实例讲述了C#定时关闭窗体的方法,分享给大家供大家参考。具体方法如下:public partial class Form2 : Form
- 这篇文章主要介绍了通过实例解析JMM和Volatile底层原理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,
- 公司的老项目要改造多租户,于是进入了大坑,本文写点遇到的坑以及解决方案,每次遇到问题在网上搜了好久,记录下来,防止以后忘掉。(一).方案网上
- 一、BitConverter 将预定义的基础类型与字节数据进行互转(Unicode)1、将值类型转成字节数组(Unicode):BitCon
- 一、何为栈?栈(stack)又名堆栈,它是一种运算受限的线性表。限定仅在表尾进行插入和删除操作的线性表。这一端被称为栈顶,相对地,把另一端称
- 最近在做一个需求:从其他系统的ftp目录下载存储图片url的文件,然后读取文件中的url地址,根据地址下载图片后按天压缩成一个包,平均一个地
- 前言在一些日常业务中,会遇到一些琐碎文件需要统一打包到一个压缩包中上传,业务方在后台接收到压缩包后自行解压,然后解析相应文件。而且可能涉及安
- 现在Java的大部分项目都是基于Maven, 在Maven项目中使用Selenium2. 非常简单。 首先你需要配置好