参数解析器之后的Java手动验证

我有一个看起来像这样的休息控制器:

@RequestMapping(
        value = "/foo",
        method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<JsonNode> getFOOs(@Valid Payload payload) {
    /** some code **/
}

Payload类看起来像这样:

@OneOrTheOther(first = "a", second = "b")
public final class Payload {
    private final String userName;
    private final String a;
    private final String b;
    @NotNull
    private final String c;
    @NotEmtpy{message="At least 1 item"}
    private List<String> names = new ArrayList<String>();
}

而ArgumentResolver如下所示:

public class PayloadArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().equals(Payload.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        if(supportsParameter(methodParameter)) {
            HttpServletRequest requestHeader = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
            String userName = requestHeader.getHeader("userName");

            ObjectMapper mapper = new ObjectMapper();
            JsonNode requestBody = mapper.readTree(CharStreams.toString(requestHeader.getReader()));

            JsonNode a = requestBody.path("a");
            String a = a.isMissingNode() ? null : a.asText();

            JsonNode b = requestBody.path("b");
            String b = b.isMissingNode() ? null : b.asText();

            JsonNode c = requestBody.path("c");
            String c = c.isMissingNode() ? null : c.asText();

            JavaType type = mapper.getTypeFactory().constructCollectionType(ArrayList.class, String.class);
            List<String> ids
                    = requestBody.path("ids").isMissingNode()
                    ? null : mapper.readValue(requestBody.path("ids").toString(), type);


            return new Payload(username, a, b, c, ids);
        }
        return null;
    }
}

目前这约占我想要的95%。 它成功检索标题和请求主体中的所有项目并创建一个Payload对象。 但创建对象后,我想运行Payload类中注释的验证,如NotNullNotEmpty或我的客户验证器OneOrTheOther

我做了一些挖掘,并在这里和这里找到了一些堆栈文章。 我不知道如何实现第一个,第二个似乎过于复杂和繁琐,所以我不想真的走这条路。 这似乎是使用validateIfApplicable方法是要走的路,但我怎么会在我的上下文中调用它?


你可以在你的类中添加一个SmartValidator实例。 只需添加:

@Autowired
SmartValidator payloadValidator;

一旦注入,你只需要调用它的validate方法,传递你的bean和错误列表。

以供参考:

SmartValidator:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/SmartValidator.html

错误:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/Errors.html


这意味着您希望在创建对象后立即运行这些验证。 如果是这种情况,那么你可以创建@Pointcut方法返回你的对象,并将调用你想要的验证@AfterReturning(方法返回对象)

     @Pointcut("execution(* YourClass.*(..))")
     public void pointcut(){}

     @AfterReturning("method that returns object")
     public final class Payload {
        private final String userName;
        private final String a;
        private final String b;
     }
链接地址: http://www.djcxy.com/p/35459.html

上一篇: Java Manual Validation after Argument Resolver

下一篇: Pearson correlation fails for perfectly correlated sets