Reputation: 165
I would like to validate the incoming json object in controller before casting it to POJO using spring jackson.
My Controller:
@RequestMapping( value = "/createContact" , method = RequestMethod.POST , consumes = MediaType.APPLICATION_JSON_VALUE , produces = MediaType.APPLICATION_JSON_VALUE )
public Contact createContact( @RequestBody Contact contact ) throws Exception
{
return ContactService.createContact( contact );
}
My Contact.java
public class Contact
{
private String ID = UUID.randomUUID().toString();
private String type = "contact";
private String category;
private String name;
}
What I am trying to achieve is that 'type' field should not be passed in the request json. I need to throw an exception if the consumer passes that value.
I can get the json as a Map or string and validate it and then cast it to POJO. But is it possible to validate it before direct casting?
Upvotes: 0
Views: 1350
Reputation: 1760
This can be done with an interceptor which will extend HandlerInterceptor. For example, you can create a ContactRequestValidator class like below.
@Component("contactRequestInterceptor")
public class ContactRequestValidator implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
// get the request payload using reader from httpServletRequest and do the validation
// and throw an exception if not valid and may handle it using an Spring MVC exception handler
}
// other two methods omitted..
}
Then register the validator interceptor with
@Configuration
public class MVCConfigurerAdapter extends WebMvcConfigurerAdapter {
@Autowired
@Qualifier("contactRequestInterceptor")
private HandlerInterceptor contactRequestValidator;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(contactRequestValidator).addPathPatterns("/api/**"); // Also have the option to use Ant matchers
}
}
Upvotes: 2