jaxbjax-rsresteasyrestletxml-binding

What is JAXB and JAXRS ? How are they related?


Sorry for this blunt question . But many use these 2 terms day in and day out yet I don't know .I did some study on this and knew what it is separately . But don't understand how it is related . I will share what I understood about these two first .

JAXB is XML-to-Java binding technology enabling transformations between schema and Java objects and between XML instance documents and Java object instances. Internally JAXB does all this conversions between xml and java . This is a parser of xml and then it knows what component in xml corresponds to what in java and it breaks . Conversion of this answer from JAXB is done by tools like xjc ( or codgen plugin) . Mapping may be like

xsd:string java.lang.String

xsd:integer java.math.BigInteger

JaxRs is different . This is set of specifications for handling requests . Meaning that it says "GET("/foo") " means handle a get call with url /foo . It only states that . How it is done ? Yes , that is called implementation of this spec . There are number of implementations like restlet , resteasy , jersey , apache cxf etc . This is analogus to logic and way you implement in maths . the algorithm idea is bucket search .This can be implemented in any way . In java terms JaxRs is interface and these 4 restlet , resteasy , jersey , apache cxf are implementations of the interface .

Now please say if my understanding is correct . Then tell how they are related . Please help . If possible a pictorial explanation will be more helpful.


Solution

  • Your understanding is basically correct. JAXB and JAX-RS are both Java Community Process (JCP) standards with multiple implementations.

    JAXB - Defines standardized metadata and runtime API for converting Java domain objects to/from XML.

    JAX-RS - Defines standardized metadata and runtime API for the creation of RESTful services. By default for the application/xml media type JAX-RS will use JAXB to convert the objects to/from XML.

    Example

    In the following example when a GET operation is performed the JAX-RS implementation will return a Customer. A JAXB implementation will be used to convert that instance of Customer to the XML that the client will actually receive.

    import javax.ws.rs.*;
    import javax.ws.rs.core.MediaType;
    
    @Path("/customers")
    public class CustomerResource {
    
        @GET
        @Produces(MediaType.APPLICATION_XML)
        @Path("{id}")
        public Customer read(@PathParam("id") int id) {
            Customer customer = new Customer();
            customer.setId(id);
            customer.setFirstName("Jane");
            customer.setLastName(null);
    
            PhoneNumber pn = new PhoneNumber();
            pn.setType("work");
            pn.setValue("5551111");
            customer.getPhoneNumbers().add(pn);
    
            return customer;
         }
    
    }