I have a break controller that looks like this:
@RequestMapping( value = "/foo", method = RequestMethod.POST) @ResponseBody public ResponseEntity<JsonNode> getFOOs(@Valid Payload payload) { }
The Payload class is as follows:
@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>(); }
And the ArgumentResolver looks like this:
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; } }
This currently represents about 95% of what I want to do. It successfully extracts all the elements from the header and body of the request and creates a Payload object. But after creating the object, I want to run checks annotated in the Payload class, for example NotNull , NotEmpty or my OneOrTheOther client validator.
I ruined a bit and found here a couple of stack articles here and here . I do not know how to implement the first, and the second seems too complicated and cumbersome, so I do not want to go this route. Using the validateIfApplicable method seems to be the way to go, but how would I call it in my context?
java spring rest validation hibernate
Richard
source share