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

时间:2016-07-22 13:27:40

标签: java spring hibernate rest validation

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

@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

我做了一些挖掘,发现了几篇文章herehere。我不知道如何实施第一个,第二个似乎过于复杂和繁琐,所以我不想真正走这条路。似乎使用validateIfApplicable方法是可行的方法,但我如何在我的上下文中调用它?

2 个答案:

答案 0 :(得分:2)

您可以在班级中添加SmartValidator实例。只需添加:

@Autowired
SmartValidator payloadValidator;

注入后,您只需要调用validate方法,传递bean和错误列表。

供参考:

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

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

答案 1 :(得分:1)

这意味着您希望在创建对象后立即运行这些验证。 如果是这种情况,那么你可以创建@Pointcut给返回你的Object的方法,并调用你想要的验证@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;
     }