使用Spring AOP和自定義註解進行參數檢查

引言

使用SpringMVC做爲Controller層進行Web開發時,常常會須要對Controller中的方法進行參數檢查。原本SpringMVC自帶@Valid和@Validated兩個註解可用來檢查參數,但只能檢查參數是bean的狀況,對於參數是String、Long等Java自帶類型的就不適用了(可是還能夠用@NotNull、@NotBlank、@NotEmpty等),並且有時候這兩個註解又忽然失效了(沒有仔細去調查過緣由)。對此,其實咱們本身也能夠利用Spring的AOP和自定義註解,本身寫一個參數校驗的功能。java

代碼示例

注意:本節代碼只是一個演示,給出一個可行的思路,並不是完整的解決方案。git

本項目是一個簡單Web項目,使用到了:Spring、SpringMVC、Maven、JDK1.8github

項目結構:
web

自定義註解:

ValidParam.java:spring

package com.lzumetal.ssm.paramcheck.annotation;

import java.lang.annotation.*;

/**
 * 標註在參數bean上,表示須要對該參數校驗
 */
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValidParam {
    
    
}

NotNull.java:apache

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:app

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:google

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:spa

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:code

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/liaosilzu2...

相關文章
相關標籤/搜索