Newsletter

JAX-RS Example of Multiple Resource Formats

Web Services » on Aug 6, 2014 { 24 Comments } By Sivateja

This article will describe how a RESTful web service produces multiple output formats.  In the previous articles we came across how a RESTful service produces either XML or JSON alone as an output, but in this article i will show you what are the changes or steps need to be followed to let the rest service to produce multiple output formats from a single method, its the real time way of creating the services.  Before you start reading this article, just have a look at the following articles for better understanding.

Exactly, exactly this current example is the combination of above two articles 🙂 I am just copy & pasting those articles and doing some changes here that’s it.

Required Files

  • pom.xml
  • web.xml
  • Customer.java
  • JsonFromRestful.java
  • RESTfulClient.java

Directory Structure

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>JAX-RS-Multiple-Output-Formats</groupId>
  <artifactId>JAX-RS-Multiple-Output-Formats</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
 
    <repositories>
           <repository>
             <id>maven2-repository.java.net</id>
              <name>Java.net Repository for Maven</name>
              <url>http://download.java.net/maven/2/</url>
              <layout>default</layout>
           </repository>
    </repositories>
 
    <dependencies>
           <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.8.2</version>
                <scope>test</scope>
           </dependency>
    
           <dependency>
                <groupId>com.sun.jersey</groupId>
                <artifactId>jersey-server</artifactId>
                <version>1.8</version>
           </dependency>
           
           <dependency>
                <groupId>com.sun.jersey</groupId>
                <artifactId>jersey-json</artifactId>
                <version>1.8</version>
          </dependency>
           
           <dependency>
                <groupId>com.sun.jersey</groupId>
                <artifactId>jersey-client</artifactId>
                <version>1.8</version>
           </dependency>
    </dependencies>
 
    <build>
       <finalName>JAX-RS-Multiple-Output-Formats</finalName>
       <plugins>
          <plugin>
              <artifactId>maven-compiler-plugin</artifactId>
                 <configuration>
                    <compilerVersion>1.5</compilerVersion>
                    <source>1.5</source>
                    <target>1.5</target>
                 </configuration>
           </plugin>
       </plugins>
    </build>
</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
  <display-name>JAX-RS-Multiple-Output-Formats</display-name>
  <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
          <param-name>com.sun.jersey.config.property.packages</param-name>
          <param-value>java4s</param-value>
        </init-param>
        <init-param>
          <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
          <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

Customer.java

package java4s;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import com.sun.xml.txw2.annotation.XmlAttribute;

@XmlRootElement(name = "customer")
public class Customer {
    
    private int custNo;
    private String custName;
    private String custCountry;
    
    @XmlAttribute
    public int getCustNo() {
        return custNo;
    }
    public void setCustNo(int custNo) {
        this.custNo = custNo;
    }
    
    @XmlElement
    public String getCustName() {
        return custName;
    }
    public void setCustName(String custName) {
        this.custName = custName;
    }
    
    @XmlElement
    public String getCustCountry() {
        return custCountry;
    }
    public void setCustCountry(String custCountry) {
        this.custCountry = custCountry;
    }   
}

JsonFromRestful.java

package java4s;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@Path("/customers")
public class JsonFromRestful {
    
    @GET
    @Path("/{cusNo}")
    @Produces("application/xml,application/json")
    //@Produces(MediaType.APPLICATION_JSON)
    public Customer produceCustomerDetailsinJSON(@PathParam("cusNo") int no) {
        
        Customer cust = new Customer();        
            cust .setCustNo(no);
            cust .setCustName("Java4s");
            cust .setCustCountry("India");
        return cust;
    }
}

RESTfulClient.java

package java4s;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class RESTfulClient {
    
    public static void main(String[] Java4s) {
        
        try {
            Client client = Client.create();    
            WebResource resource = client.resource("http://localhost:2015/JAX-RS-Multiple-Output-Formats/rest/customers/100");    
            ClientResponse response = resource.accept("application/json").get(ClientResponse.class);
            
            if(response.getStatus() == 200){
                
                String output = response.getEntity(String.class);
                System.out.println(output);    
                
            }else System.out.println("Somthing went wrong..!");        
    
          } catch (Exception e) {    
                  e.printStackTrace();    
          }
    
        }   
}

Execution & Output

  • Eclipse > right click on RESTfulClient.java > Run As > Run on Server
  • As per above program it will give you the JSON output
  • If you want to see the output in XML format. Open RESTfulClient.java > in line number 14 replace that line with

    ClientResponse response = resource.accept(“application/xml“).get(ClientResponse.class);

    and the XML output will be

 

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

24 Responses to “JAX-RS Example of Multiple Resource Formats”
  1. Madiraju Krishna Chaitanya says:

    Hi Sivateja Kandula Ji,Good Morning.Thanks a LOT for providing and sharing knowledge on WebServices with all of us.I was searching for an authentic content with real time examples,that is when I found your site.One small favor from your side.Can you please share a real-time project(or a dummy one) that you have created w.r.t SOAP UI and RESTful webservices…?.I am learning webservices concepts and I would like to have a projects(for SOAP and RESTful) for my understanding.Kindly share the project code if you have with me.Thanks in Advance.
    You can share the code(project)with my email id: chaitanya.mca@gmail.com.Thanks Again. ~Chaitanya.

  2. I don’t know how much effort that Java4S team kept in making this Restful web services tutorial but for me it tooks just 4-5 hours to complete all the examples…i don’t know much about web services before visiting this site.

    Thanks a lot to Java4S team. Wish your team to keep up the good work.

  3. Thirupathi says:

    Hi Java4s Team,
    You are providing good tutorial on Java.. Everyday I’m following your site. I have learnt lot of frameworks from your site.Thank you so much. Please could you provide JSF tutorial also.Anyways thanks..

  4. sandeep says:

    Hi dear,
    This is very helpfull site for beginner to learn the webservice.

  5. Varshit says:

    hi sivateja,

    it is amazing, before visiting this site, i was having the small doubts, but now it is clear.. very nice tutor…
    sivateja, can u provide any sample or dumy real time project or steps to develop the real time project. it will be very useful to me.
    If u kindly provide the project on RESTful. Kindly share the project code if you have. Thanks in Advance. You can share the code(project)with my email id – asrikanthjava9885@gmail.com
    waiting for your positive reply

    Thks…

  6. Binoy KB says:

    Just Awesome Tutorial on Web Service.

  7. Venkata says:

    Hi Sir,your Tutorials are the BEST among the Web for Java.looking for Further java Stuff from you.Thanks Venkata Sriram

  8. Mahi says:

    hi Dear,
    Nice Tutorial . I was seeking good material about REST Full web services from the 2 year but did not get any good material .the way you write is it is amazing its very help full to the beginner . they can learn quick.

    One more request to you can you provide a real example of client Rest full .
    Suppose i have published the Web services and consumer wants to access this web service . how they can access I mean have to do tie up between consumer and publisher. other wise any body can acccess thier web service if I know the URL of Web service.

  9. kesavamoorthy says:

    Hi Java4s Team,

    Its realy good tutorial for all, i learn lot form this site and please work on more core java.

    Thanks ,
    kesavan

  10. kesavamoorthy says:

    Hi ,

    Can you give some example of Restful service Authentication.

  11. indu says:

    Nice Tutorial . I was looking real time project on RESTful web services.
    can u provide steps how to configure RESTful with spring.

    kindly provide the project on RESTful. Kindly share the project code if you have. Thanks in Advance. You can share the code(project)with my email id.

  12. Ganesh says:

    Hi Sivateja,

    I saw your tutorial ,i got a few knowledge on web service , thank you for sharing examples and web service picture.

  13. Reddy says:

    hi Indu

    I have done some RESTful (jersey,apache cxf) examples using spring.if u want drop a mail to akkireddy61@gmail.com.

  14. Rahul Nirgude says:

    Hi.. thanks for this website. This is really helpful

  15. venkat says:

    Hi

    I was followed u r site In this site I learned good things but now I am learning web services but I want real time project . I hope u definitely will share the project code ASAP..

    this is my mail id venkt.java008@gmail.com

  16. Raajkiran says:

    Hi Java4s Team,

    I was followed you web services tutorials regularly, here i want to know how to apply these restful concepts in project.can you help me ,if you have project(dummy) you can send me this email:rajkiran.rajkumar@gmail.com.Thanks in advance.

  17. Suvakant says:

    Hi java4s Team,
    I really impressed with the tutorial, dont know how much effort u guys put for this, for me it took hardly take 4 hr to learn webservice, i was not aware of any thing priorto that , i am prety much confident on webservice now. Thnks a lot team 🙂

  18. Sasmita says:

    Thanks java4s team. Very very good tutotial.

  19. Nivas says:

    Thanks a lot.. Really nice explanation on each terms. Keep the good work..

  20. Qamruddin says:

    amazing tutorial ..very easy to learn 🙂

  21. Veera says:

    It is good site for simple learing web services..

  22. kumarraja says:

    How you are getting customer details without DAO class

  23. Chandana says:

    Thank you for valuable tutorials.

  24. Hi siva,

    I have one doubt regarding webservices. when we use jersey webservice annotations in normal java application in one class, we configure that file under <inti-param> of web.xml.
    If we have more that one file using restful (jersey) webservices then how to configure them under init-param tag.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.