springMvc,SpringBoot自定义注解校验接收参数不能为空
在很多时候我们的Controller是需要对接收参数进行校验的,如果为空的会影响一些操作.
然后自己写了一个自定义注解实现了参数校验
上代码~~~~~~~~~~~~~~
首先是自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author hef
* @date 2019-03-25 14:17
*/
@Target({ElementType.PARAMETER})//参数级别
@Retention(RetentionPolicy.RUNTIME) //注解保留到运行阶段
public @interface ParamsNotNull {
}
然后是编写一个处理器
import com.alibaba.fastjson.JSONObject;
import com.lyorcw.system.common.Constant;
import com.lyorcw.system.common.ParamsNotNull;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;
/**
* @author hef
* @date 2019-03-25 14:26
*/
public class CheckParamsInterceptor extends HandlerInterceptorAdapter {
private static Logger LOG = LoggerFactory.getLogger(CheckParamsInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (!(handler instanceof HandlerMethod)) {
LOG.warn("UnSupport handler");
return true;
}
//拿到该方法上加了注解的参数名称
List<String> list = getParamsName((HandlerMethod) handler);
for (String s : list) {
//获取到参数名称并判断是否为空
String parameter = request.getParameter(s);
if (StringUtils.isEmpty(parameter)){
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", Constant.error);
jsonObject.put("msg", "必传参数错误");
response.setHeader("Content-type", "application/json;charset=UTF-8");
response.getWriter().write(jsonObject.toJSONString());
return false;
}
}
//如果拿到的对象为空,说明没有此注解,直接放行
return true;
}
/**
* 拿到在参数上加了该注解的参数名称
*/
private List getParamsName(HandlerMethod handlerMethod) {
Parameter[] parameters = handlerMethod.getMethod().getParameters();
List<String> list = new ArrayList<String>();
for (Parameter parameter : parameters) {
if(parameter.isAnnotationPresent(ParamsNotNull.class)){
list.add(parameter.getName());
}
}
return list;
}
}
接着是在配置文件生效
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author hef
* @date 2019-03-25 15:09
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
CheckParamsInterceptor checkSourceInterceptor = new CheckParamsInterceptor();
@Override
public void addInterceptors(InterceptorRegistry registry) {
//如果除了接口的请求还有其他请求的话可以在所有的接口前面加个前缀区分开
registry.addInterceptor(checkSourceInterceptor).addPathPatterns("/**");
}
}
接着是在Controller的接口参数上面用自定义注解
这个时候在执行这个方法之前拦截器会拦截到被请求的接口,去校验接口参数上面是否有这个注解,如果有注解的则校验参数是否为空,如果为空就会被打回去
结果:
只要参数是空串或者为null就可以拦截下来