请求验证时响应空响应错误(Apache CXF,JAX-RS)

时间:2017-08-09 10:12:55

标签: spring-boot cxf bean-validation

我正在使用Apache CXF,JAX-RS和JSR-303验证。 验证工作正常,对于无效的请求对象,我在日志中有HTTP 400响应和验证错误,但我的响应正文是空的。 如何在响应正文中获得有关验证错误的详细信息?

我使用Spring Boot 1.5.6,Apache CXF 3.1.2。

我在java配置中设置了CXF

@Bean
BeanValidationFeature commonValidationFeature() {
    return new BeanValidationFeature();
}

@Bean
ValidationExceptionMapper exceptionMapper() {
    return new ValidationExceptionMapper();
}

@Bean
JAXRSParameterNameProvider parameterNameProvider() {
    return new JAXRSParameterNameProvider();
}

@Bean
BeanValidationProvider validationProvider() {
    return new BeanValidationProvider(parameterNameProvider());
}

@Bean
JAXRSBeanValidationInvoker validationInvoker() {
    final JAXRSBeanValidationInvoker validationInvoker = new JAXRSBeanValidationInvoker();
    validationInvoker.setProvider(validationProvider());
    return validationInvoker;
}

@Bean
JAXRSBeanValidationFeature validationFeature() {
    final JAXRSBeanValidationFeature feature = new JAXRSBeanValidationFeature();
    feature.setProvider(validationProvider());
    return feature;
}

然后我使用这些bean来设置org.apache.cxf.endpoint.Server

JAXRSServerFactoryBean serverFactoryBean = new JAXRSServerFactoryBean();
        serverFactoryBean.setProvider(new JacksonJsonProvider(objectMapper));
        serverFactoryBean.setProvider(exceptionMapper());            
serverFactoryBean.setFeatures(Arrays.asList(commonValidationFeature(), 
swagger2Feature()));
        serverFactoryBean.setBus(bus);
        serverFactoryBean.setInvoker(validationInvoker());
        serverFactoryBean.setServiceBeans(Collections.singletonList(myApiImplementation));
        return serverFactoryBean.create();

如何在响应正文中获得有关验证错误的详细信息?是否有一些合理的默认值(如在Spring MVC中?)我可以自定义验证错误的错误响应吗?

1 个答案:

答案 0 :(得分:1)

org.apache.cxf.jaxrs.validation.ValidationExceptionMapper的默认实现未提供有关响应正文中验证错误的详细信息,但可以轻松更改。在创建ValidationExceptionMapper的新实例时,只需要.setAddMessageToResponse(true);

然后,响应正文中会出现有关验证错误的详细信息。