[英]Validate Json Object before casting it to POJO - using @requestBody
我想在使用spring jackson将其强制转换为POJO之前,在控制器中验证传入的json对象。
我的控制器:
@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 );
}
我的Contact.java
public class Contact
{
private String ID = UUID.randomUUID().toString();
private String type = "contact";
private String category;
private String name;
}
我正在尝试实现的是,不应在请求json中传递“类型”字段。 如果消费者通过该值,则需要抛出异常。
我可以将json作为Map或字符串获取并进行验证,然后将其转换为POJO。 但是可以在直接投放之前对其进行验证吗?
可以使用将扩展HandlerInterceptor的拦截器完成。 例如,您可以创建如下的ContactRequestValidator类。
@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..
}
然后向注册验证器拦截器
@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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.