在将Json对象转换为POJO之前验证它 - 使用@requestBody

时间:2016-03-23 10:01:41

标签: java json spring validation

我想在使用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 );
        }

My Contact.java

public class Contact
{

    private String ID = UUID.randomUUID().toString();

    private String type = "contact";

    private String category;

    private String name;
}

我想要实现的是' type'字段不应该在请求json中传递。如果消费者传递了该值,我需要抛出异常。

我可以将json作为Map或字符串进行验证,然后将其转换为POJO。但是在直接投射之前是否有可能对其进行验证?

1 个答案:

答案 0 :(得分:2)

这可以通过延伸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
    }
}