Jersey (1.19.1)-XML support

Source: Internet
Author: User

As you probably already know, Jersey uses messagebodywriters and messagebodyreaders to parse incoming request and CREA Te outgoing responses. Every user can create its own representation but ... this is not recommended a-to-do things. XML is proven-interchanging information, especially in Web services. Jerseys supports low level data types used for direct manipulation and JAXB XML entities.

Low Level XML Support

Jersey currently support several low level data types: StreamSource , SAXSource , DOMSource and Document . You can use these types as return type or method (Resource) parameter. Lets say we want to test this feature and we have HelloWorld for sample as starting point. All we need to does is add methods (resources) which consumes and produces XML and types mentioned above would be used.

@Path ("1") @POST Publicstreamsource Get1 (Streamsource streamsource) {returnStreamsource;} @Path ("2") @POST PublicSAXSource Get2 (SAXSource SAXSource) {returnSaxSource;} @Path ("3") @POST Publicdomsource Get3 (Domsource domsource) {returnDomsource;} @Path ("4") @POST PublicDocument GET4 (document document) {returndocument;}

Both messagebodyreaders and Messagebodywriters are used in the this case, all we need be do POST request with some XML documen T as a request entity. I want to keep the as simple as possible so I ' m going to send only the root element with no content: "<test />" . You can create a Jersey client to do or use some the other tool, for example as curl I did. (curl -v http://localhost:9998/helloworld/1 -d "<test />"). You should get exactly same XML from our service as was present in the request; In this case, XML headers is added to response but content stays. Feel free to iterate through all resources.

Getting started with JAXB

Good start for people which already has some experience with JAXB annotations are JAXB sample. You can see various usecases there. This text was mainly meant for those who has prior experience with JAXB. Don ' t expect that all possible annotations and their combinations would be covered in this chapter, JAXB (JSR 222 Implement ation) is pretty complex and comprehensive. But if you just want to know how can interchange XML messages with your REST service, you is looking at right chapter .

Lets start with simple example. Lets say we have class and Planet service which produces "planets":

//Planet class@XmlRootElement Public classPlanet { Public intID;  PublicString name;  Public Doubleradius;}//Resource class@Path ("Planet") Public classResource {@GET @Produces (mediatype.application_xml) PublicPlanet getplanet () {Planet P=NewPlanet (); P.id= 1; P.name= "Earth"; P.radius= 1.0; returnp; }} 

You can see there are some extra annotation declared on Planet class. Concretely XmlRootelement . What it does? This was a JAXB annotation which maps Java class to XML element. We don ' t need specify anything else, because is very simple class and all fields are public Planet . In the this case, the XML element name is derived from the class name or you can set the Name property: @XmlRootElement(name="yourName") .

Our resource class would respond to get/planet with

<?XML version= "1.0" encoding= "UTF-8" standalone= "yes"?><Planet>    <ID>1</ID>    <name>Earth</name>    <radius>1.0</radius></Planet> 

Which might be exactly what we want ... or not. Or we might not really care, because we can use the Jersey client for making requests to this resource and this is easy as: . There is pre-created WebResource object which points to our applications context root and we simpli add path (in our Clase Its "planet"), the Accept header (not mandatory, but service could provide different content based on the this header; for Exampl E text/html can is served for web browsers) and at the end we specify, we are expecting Planet class via GET request.

There may is need for don't just producing XML, we might want to consume it as well.

@POST @consumes (mediatype.application_xml)  Public void setplanet (Planet p) {    System.out.println ("setplanet" + p);}

After valid request was made (with Jersey client you can do webResource.path("planet").post(p); ), service would print out string representation of Planet, Which can look like Planet{id=2, name=‘Mars‘, radius=1.51} .

If there is a need for some other (non default) XML representation, and other JAXB annotations would need to be used. This process is a usually simplified by generating Java source from XML Schema which are done by XJC. XJC is XML to Java compiler and was part of JAXB. See JAXB home page for further details.

POJOs

Sometimes you can ' T/don ' t want to add JAXB annotations to source code and you still want to the resources consuming and Producing XML representation of your classes. In this case, JAXBElement class should. Let's redo planet resource But the this time we won ' t has XmlRootElement annotation on Planet class.

@Path ("Planet") Public classResource {@GET @Produces (mediatype.application_xml) PublicJaxbelement<planet>getplanet () {Planet P=NewPlanet (); P.id= 1; P.name= "Earth"; P.radius= 1.0; return NewJaxbelement<planet> (NewQName ("Planet"), planet.class, p); } @POST @Consumes (mediatype.application_xml) Public voidSetplanet (jaxbelement<planet>p) {System.out.println ("Setplanet" +P.getvalue ()); }} 

As you can see, everything are little more complicated with jaxbelement. This is the because now need to explicitly set element name for Planet class XML representation. Client side is even more ugly than server side because what can ' t do JAXBElement<Planet>.class Jersey client API provides the how to Workaro und it by declaring subclass of GenericType .

//GETGenerictype<jaxbelement<planet>> Planettype =NewGenerictype<jaxbelement<planet>>() {}; Planet Planet= (Planet) webresource.path ("Planet"). Accept (Mediatype.application_xml_type). Get (Planettype). GetValue (); System.out.println ("### " +planet);//POSTPlanet p =NewPlanet ();// ...Webresource.path ("Planet"). Post (NewJaxbelement<planet> (NewQName ("Planet"), planet.class, p));

Using Custom Jaxbcontext

In some scenarios you can take advantage of using custom JAXBContext . Creating JAXBContext is expensive operation and if you already has one created, same instance can be used by Jersey. Other possible usecase-the-is-when-you-need to set some specific things-jaxbcontext, for example set different CLA Ssloader.

@Provider Public classPlanetjaxbcontextproviderImplementsContextresolver<jaxbcontext> {    PrivateJaxbcontext context =NULL;  PublicJaxbcontext GetContext (class<?>type) {        if(Type! = Planet.class)            return NULL;//we don ' t support nothing else than Planet                if(Context = =NULL) {            Try{Context= Jaxbcontext.newinstance (Planet.class); } Catch(jaxbexception e) {//log warning/error; null would be returned which indicates the This//provider won ' T/can ' t be used.            }        }        returncontext; }}

Sample above shows simple JAXBContext creation, all need to does is put this @Provider annotated class somewhere where Jersey can Find it. The Users sometimes has problems with using the provider classes on client side, so just for Reminder-you has to declare them In client config (Cliend does does anything like the package scanning do by server).

New defaultclientconfig (); Cc.getclasses (). Add (Planetjaxbcontextprovider. class  = Client.create (cc);

Jersey (1.19.1)-XML support

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.