2017-03-16 96 views
0

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

+0

有'BeanValidationFeature'需要被启用。如果您使用的是基于xml的配置,您必须像这样注入此功能http://cxf.apache.org/docs/features.html –

回答

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>