用于在REST API中验证XML请求的拦截器

时间:2017-03-16 10:34:19

标签: java spring rest cxf interceptor

我正在开发一个REST API,它是 @POST @Consumes MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON 。我需要为传入的请求实现验证。我不想让Bean Level验证JSR-303。我需要一个Validation类来处理所有的验证,我需要在Unmarshalling之前为传入的XML请求配置拦截器。我研究了Apache cxf拦截器,主要是你启用Bean验证。我该怎么做?

1 个答案:

答案 0 :(得分:0)

我已经找到了如何在不使用BeanValidationFeature的情况下执行此操作的方法。

public class YourFilter implements ContainerRequestFilter{

     @Override
      public void filter(ContainerRequestContext request){
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        final InputStream inputStream = request.getEntityStream();
        final StringBuilder builder = new StringBuilder();
        try
        {
            IOUtils.copy(inputStream, outStream);
            byte[] requestEntity = outStream.toByteArray();
            if (requestEntity.length == 0) {
                builder.append("");
            } else {
                builder.append(new String(requestEntity,"UTF-8"));
                request.setEntityStream(new ByteArrayInputStream(requestEntity));
                setRequest(builder.toString());
                validateYourRequest(builder.toString());
            }
        }catch (Exception ex) {
            logger.log(Level.TRACE,"Error occured while converting the request into Stream",ex.getCause());
        }
    }
}

在application.context.xml

<bean id="YourFilter" class="com.test.YourFilter"/>

<jaxrs:server id="restContainer" address="/">

    <jaxrs:serviceBeans>
        <bean class="com.test.YourController" />
    </jaxrs:serviceBeans>

    <jaxrs:extensionMappings>
        <entry key="json" value="application/json" /> 
        <entry key="xml" value="application/xml" />  
    </jaxrs:extensionMappings>

    <jaxrs:providers>
        <ref bean="jsonProvider" />
        <ref bean="jaxbXmlProvider" />
        <ref bean="YourFilter"/>
    </jaxrs:providers>
</jaxrs:server>