【问题标题】:Validate Json Object before casting it to POJO - using @requestBody在将其转换为 POJO 之前验证 Json 对象 - 使用 @requestBody
【发布时间】:2016-03-23 10:01:41
【问题描述】:

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

我的联系人.java

public class Contact
{

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

    private String type = "contact";

    private String category;

    private String name;
}

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

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

【问题讨论】:

  • 由于对象是使用 Jackson 映射解析的,因此请使用 Jackson XML 注释相应地注释您的对象。那应该可以解决您的问题。
  • @Schaka - 对象级别的注释将是全局的。对于某些请求,我需要阻止请求有效负载中的“类型”字段并抛出异常,但与其他请求一样,我需要接受“类型”字段。你能帮我解决这个问题吗?

标签: java json spring validation


【解决方案1】:

这可以通过扩展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
    }
}

【讨论】:

    猜你喜欢
    • 2017-08-23
    • 1970-01-01
    • 2011-08-18
    • 2015-02-17
    • 2021-12-31
    • 1970-01-01
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多