springboot 忽略接收请求中的参数
一、场景说明
在一些开发场景中,特别是前后端分开开发的场景中,由于后端接口采用的VO接收前端请求传递的参数,但是前端开发小伙伴可能会把vo中所有属性不进行过滤就直接调用接口,这样会导致后端api由于不需要某些字段而导致api运行失败,比如:id字段等。
二、开发环境
开发工具: IDEA 开发语言: JAVA 1.8 开发环境: Springboot 2.4.13
三、实现思路
- 使用Java的注解技术,定义一个ReceiveIgnoreParam注解,作用在Controller的需要忽略接收属性的方法上。
- 通过spring切面编程技术来实现对方法注解的操作,其判断方法参数中是否包含需要忽略的属性,如果存在直接设置为null或者空串
四、具体实现
package com.rewloc.annotation;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Target(ElementType.METHOD)
public @interface ReceiveIgnoreParam {
String[] fieldName();
}
package com.rewloc.aop;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.BooleanUtil;
import com.rewloc.annotation.ReceiveIgnoreParam;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.Arrays;
@Aspect
@Component
public class ReceiveIgnoreParamAop {
private static final String ID = "id";
@Pointcut("@annotation(com.rewloc.ReceiveIgnoreParam)")
private void ignoreReceiveParam() {
}
@Around(value = "ignoreReceiveParam()")
public Object doAround(ProceedingJoinPoint point) {
try {
MethodSignature methodSignature = (MethodSignature) point.getSignature();
ReceiveIgnoreParam ignoreReceiveParam = methodSignature.getMethod().getAnnotation(ReceiveIgnoreParam.class);
Object[] args = point.getArgs();
for (Object arg : args) {
try {
cleanValue(arg, field);
} catch (Exception e) {
}
});
}
return point.proceed(args);
} catch (Throwable e) {
throw new RuntimeException("系统繁忙,请稍后再试!");
}
}
private void cleanValue(Object obj, String fieldName) throws IllegalAccessException {
Class<?> aClass = obj.getClass();
Field[] fields = aClass.getDeclaredFields();
for (Field field : fields) {
if (fieldName.equals(field.getName())) {
field.setAccessible(true);
field.set(obj, null);
}
}
}
}
package com.rewloc.vo
import lombok.Data;
@Data
public class ReceiveIgnoreParamVO {
private String id;
private String name;
private String sex;
private int age;
private String birthdate;
}
package com.rewloc.web;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/receive/ignoreParam")
public class ReceiveIgnoreParamController {
@PostMapping("/hello")
@ReceiveIgnoreParam(fieldName = {"id", "name"})
public String selectPage(ReceiveIgnoreParamVO vo) {
return JSONObject.toJSONString(vo);
}
}
五、总结
只要注解和spring切面结合可以做很多事情。
|