1:先实现注解,因为参数的个数不定,就用数组
/** * @description 参数校验 * @Author: Mr.Li * @create: 2020/4/25 0025 15:27 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ParameterCalibration { String[] value() default {}; }
2:编写拦截器
/** * @description: 参数拦截校验 * @Author: Mr.Li * @create: 2020/4/25 0025 15:30 */ public class ParameterCheckInterceptor implements Interceptor { @Override @ParameterCalibration public void intercept(Invocation inv) { ParameterCalibration parameterCalibration = inv.getMethod().getAnnotation(ParameterCalibration.class); if (parameterCalibration != null) { for (String param : parameterCalibration.value()) { String value = inv.getController().get(param); if (value == null || value.trim().isEmpty() || value.trim().equals("null")) { inv.getController().setAttr("code", ResponseCode.PARAMTER_NULL); inv.getController().setAttr("message", "【" + param + "】不存在或不能为空"); inv.getController().renderJson(); return; } } } inv.invoke(); } }
3:添加拦截器到路由中
/** * @description 客户端路由 * @Author: Mr.Li * @create: 2020/4/25 0025 14:55 */ public class ClientRoutes extends Routes { @Override public void config() { addInterceptor(new ParameterCheckInterceptor());//请求参数校验 //addInterceptor(new ClientTokenInterceptor());//Token验证 //addInterceptor(new CacheInterceptor());//缓存 add("/demo/user", UserController.class);//用户 } }
4:在需要校验参数的方法上加入拦截
@ParameterCalibration("userId") public void demo() { int userId = getInt("userId"); User user = new User().findById(userId); returnSuccessResult(user); }