2017-03-16 121 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>