虚位以待(AD)
虚位以待(AD)
首页 > 软件编程 > Java编程 > 详解使用Spring AOP和自定义注解进行参数检查

详解使用Spring AOP和自定义注解进行参数检查
类别:Java编程   作者:码皇   来源:互联网   点击:

本篇文章主要介绍了详解使用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)@Documentedpublic @interface ValidParam {
    }

NotNull.java:

    package com.lzumetal.ssm.paramcheck.annotation;
    import java.lang.annotation.*;
    @Target({
    ElementType.FIELD, ElementType.PARAMETER}
    )@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @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)@Documentedpublic @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@Componentpublic 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;
    @Controllerpublic 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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

  • Spring AOP注解失效的坑及JDK动态代理
  • spring AOP自定义注解方式实现日志管理的实例讲解
  • Spring Aop之AspectJ注解配置实现日志管理的方法
  • 详解使用Spring Boot的AOP处理自定义注解
  • 关于spring中aop的注解实现方法实例详解
  • 使用Spring的注解方式实现AOP实例
  • Spring AOP 基于注解详解及实例代码
  • Spring AOP 自定义注解的实现代码
  • spring中AOP 注解开发示例详解
相关热词搜索: Spring AOP 参数检查 spring自定义参数注解