JAXB - Preserving Namespace Prefixes in CXF WebServices

Follow the below steps if you want to preserve the namespace prefix values consistent.

First define a namespace prefix map, say JAXBNamespacePrefixesMap as below:

<util:map id="JAXBNamespacePrefixesMap">
   <entry key="http://www.texient.com/mail" value="ns1" />
   <entry key="http://www.texient.com/account" value="ns2" />
   <entry key="http://www.texient.com/contact" value="ns3" />
   <entry key="http://www.texient.com/address" value="ns4" />
   <entry key="http://www.texient.com/category" value="ns5" />
</util:map>

Now set this map as namespacePrefixes in JAXBElementProvider.

<bean id="jaxbProvider" class="org.apache.cxf.jaxrs.provider.JAXBElementProvider">
   <property name="jaxbElementClassMap" ref="JAXBElementClassMap" />
   <property name="marshallAsJaxbElement" value="true" />
   <property name="unmarshallAsJaxbElement" value="true" />
   <property name="collectionWrapperMap" ref="JAXBElementClassMap" />
   <property name="namespacePrefixes" ref="JAXBNamespacePrefixesMap" />
</bean>

In the server configuration you will have jaxbProvider as a provider.

<jaxrs:server id="CXFService" address="/" >
   <jaxrs:extensionMappings>
      <entry key="json" value="application/json" />
      <entry key="xml" value="application/xml" />
   </jaxrs:extensionMappings>
   <jaxrs:serviceBeans>
      <ref bean="CXFServiceBean"/>
   </jaxrs:serviceBeans>
   <jaxrs:providers>
         <ref bean="jaxbProvider" />
         <ref bean="jsonpProvider" />            
    </jaxrs:providers>
    <jaxrs:inInterceptors>
       <ref bean="jsonpInInterceptor"/>
    </jaxrs:inInterceptors>
    <jaxrs:outInterceptors>
        <ref bean="jsonpOutInterceptor"/>
      </jaxrs:outInterceptors>         
</jaxrs:server>

That's it! You will see the namespace prefix as defined in the mapping.

<ns1:person xmlns:ns1="http://www.texient.com/mail" xmlns:ns2="http://www.texient.com/account" xmlns:ns3="http://www.texient.com/contact" xmlns:ns4="http://www.texient.com/address" xmlns:ns5="http://www.texient.com/category">
   <ns3:account>
      <ns4:address>Your address</ns4:address>
      <ns5:category>Customer</ns5:category>
   </ns3:account>
</ns1:person>

Comments

Popular posts from this blog

Induction Cooker Showing an Error Code? Induction Cooker Error Codes Explained

HDFC Bank introduces Missed Call Service to know Account Balance

Top Travel Websites Reviewed - Makemytrip, Yatra, ClearTrip, Ezeego1 and TravelGuru