一、注释类ParamNull

使用此注释表示该参数可为空,其余参数都不能为空

@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ParamNull {
}

二、拦截器ParamsInterceptor

public class ParamsInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        List<String> list = getParamsName((HandlerMethod) handler);
        for (String param : list) {
            //判断参数内容是否为空
            String content = request.getParameter(param);
            if (StringUtils.isBlank(content)) {
                Info info = InfoUtil.getInfo(600, param + "参数不能为空");
                ResponseUtil.responseMessage(response, info);
                return false;
            }
        }
        return true;
    }

    /**
     * 获取没有添加ParamNull注解的参数
     */
    private List<String> getParamsName(HandlerMethod handlerMethod) {
        Parameter[] parameters = handlerMethod.getMethod().getParameters();
        List<String> list = new ArrayList<>();
        for (Parameter parameter : parameters) {
            if (!parameter.isAnnotationPresent(ParamNull.class)) {
                list.add(parameter.getName());
            }
        }
        return list;
    }
}

三、配置类配置拦截器

@Configuration
public class WebConfig implements WebMvcConfigurer {
    //注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //参数不能为空的注释配置
        registry.addInterceptor(new ParamsInterceptor())
                .addPathPatterns("/**");
    }
}

四、使用

@ParamNull注解标记在参数前,表示该参数可为空

    @PostMapping("/insertComment")
    Info insertComment(@RequestParam Integer questionId,
                       @RequestParam(defaultValue = "0") @ParamNull Integer lastCommentId,
                       @RequestParam String message) {
        Comment comment = new Comment();
        comment.setQuestionId(questionId);
        comment.setLastCommentId(lastCommentId);
        comment.setMessage(message);
        return commentService.insertComment(comment);
    }

hhhhh