Thursday, November 8, 2012

Developing a RESTful Java Web service in Eclipse Indigo using maven

RESTful web services have become the kind of de-facto in the present days, thanks to Roy Fielding's dissertation stating its advantages. Developing these is also easy to someone who is NOT very accustomed to SOAP-WSDL based services. However it is little difficult to someone who has been working in the arena of SOAP, although not tough.
I believe a great deal of difficulty in developing RESTful web services is because of the unavailability of a uniform IDE that makes life easier for a developer. Although Netbeans has a very good abstracted mechanism that lets users develop RESTful web services with no pain, I don't prefer working with it, nor would I recommend anyone to use it. The major reason for the same is the highest levels of abstraction it offers to the developer which makes it difficult for him/her to understand the flow.
In this article I will try to walk you through the steps involved in successfully developing a RESTful java web service in eclipse using maven.
This article uses Eclipse Indigo, maven2, Sonatype M2Eclipse, Apache Tomcat 7.
Step1: Go to Help->Install New Software->Add. Enter the name as "m2eclipse" (you can give any name you wish to) and the location  http://m2eclipse.sonatype.org/sites/m2e. Then you will find the software "Maven Integration for Eclipse". Install it.
Step2: Developing a Dynamic web project also requires installing the software, "Maven Integration for Eclipse WTP", which can be found in the repository, http://m2eclipse.sonatype.org/sites/m2e-extras. Proceed similarly to add this repository too.
Step3: Now choose the directory where the workspace needs to be stored and run the folowing command.
mvn -Declipse.workspace= eclipse:add-maven-repo
This will be the local maven repository.
Step4: Now New->Project->Maven Project->Select Artifact ID as maven-archetype-webapp->Give groupID (similar to package name), artifact ID (similar to project name) and click Finish.
Step5: Now a directory structure will be formed as follows.

Step6: This is the most important step. The directory structure formed by default has to be changed a little. As per the Maven directory structure specifications, all the source java files (services) need to be inside /src/main/java. Follow the following steps to change the directory structure.

  • Remove src/main/resources under Java Resources
  • Add java folder to src/main directory
  • Right click on Java Resources->New->Source Folder and give the previously added java folder in the Folder name and click Finish as shown below.


  • The final directory structure should look like this.


Step7: Now add the following lines to pom.xml.
  

 
  maven2-repository.java.net
  Java.net Repository for Maven
  http://download.java.net/maven/2/
  default
 

  
    
   com.sun.jersey
   jersey-server
   1.8
    
  

This will essentially indicate the maven, the url to look for repositories while building. Also the dependency here is as required by the Jersey specification.
Step8: Now write the java service in a class file. Create a new class and add code similar to this. The annotations @Path along with @GET and @PathParam are very important, you can look into JSR311 API for details on this.
package com.rest.test;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
 
@Path("/test")
public class TestRest {
 
 @GET
 @Path("/{name}")
 public Response getMsg(@PathParam("name") String name) {
 
  String output = "Hello, " + name;
 
  return Response.status(200).entity(output).build();
 
 }
 
}

 Step9: Now we are required to update web.xml according to Jersey reference implementation. web.xml should look like this.

 Restful Web Application
 
 
  TestServlet
  
                     com.sun.jersey.spi.container.servlet.ServletContainer
                
  
       com.sun.jersey.config.property.packages
       com.rest.test
  
  1
 
 
 
  TestServlet
  /resources/*
 
 


These steps should essentially deploy a RESTful java web service successfully and you can test it by hitting the following URL.
http://localhost:8080/resources/test/kausal
And you should see the output "Hello, kausal". Here "kausal" is the parameter passed to the method response().

I hope this gives basic idea about how to develop a RESTful java web service with Jersey reference implementation in eclipse using maven. Please feel free to post your queries/comments.

34 comments:

  1. Great article for beginners. Keep it up.

    ReplyDelete
    Replies
    1. I too find the article great as it has described everything so perfectly following each steps.

      Website design company in Mumbai

      Delete
  2. Replies
    1. TestServlet is the name given by us for the ServletContainer class which is present in the Jersey Jar, taken care by maven.
      It is similar to web.xml for any servlet application where you give servlet-name and url-pattern.
      Here we say, upon receiving a request of type /resources/*, redirect to TestServlet, which is nothing but ServletContainer and the specific class to be loaded is specified by the package name in the init-param value.
      Let me know if you have anymore questions.

      Delete
  3. Hi Kausal Malladi,

    Thank you for a nice tutorial. Could you make more tutorials about connecting RESTful service server to database and have a client project remote to that server (using Eclipse Indigo)?

    Best regards.

    ReplyDelete
  4. Hi Kausal Malladi,

    I did this tutorial, but it only works for me if I use like this:
    http://localhost:8080/TestRest/resources/test/kausal

    If I try http://localhost:8080/resources/test/kausal, it doesn't work.
    Do you know why?
    Thank you

    ReplyDelete
    Replies
    1. Hi Juliano,
      It rightly doesn't work because a web application should have a name and a deployment descriptor, with the resources developed being part of it.

      http://localhost:8080/TestRest will essentially take you to the TestRest directory of CATALINA_HOME/webapps
      All your web services, rather any resources have to be a part of a web application and hence you cannot access using http://localhost:8080/resources/test/kausal in which the web application name specified is "resources" which is not found in the server.

      http://localhost:8080/TestRest/resources/test/kausal hits the server, sees the TestRest directory of CATALINA_HOME/webapps, checks for the deployment descriptor where URL pattern is "/resources/*" and hence loads the classes, "test" is the path annotated in our service which needs a string argument "kausal".

      Hope I am able to clear your doubt.

      Read through this link for more information on the directory structure of a web application deployed in tomcat
      http://www.coreservlets.com/Apache-Tomcat-Tutorial/web-applications.html

      You may also go through this for tomcat's directory structure
      http://www.ntu.edu.sg/home/ehchua/programming/howto/Tomcat_More.html

      Let me know if you have anymore issues.

      Regards.

      Delete
  5. Thanks for your clear cut basic example

    ReplyDelete
  6. Thanks.... after googling for a couple of days .. at last I found this tutorial. Though I had to make a couple of changes, but still it helped me a lot!!

    ReplyDelete
  7. Hi Kausal Malladi,
    Can you help me how can i consume this Web Service in PHP client.
    Regards.

    ReplyDelete
    Replies
    1. Hi Ammar,

      This link could help you get some insights about how it can be done. I don't have a better self-made tutorial like this.

      http://developer.yahoo.com/php/tutorials/water_bug_tutorial-making_rest_request.html

      Regards.

      Delete
    2. Hi,
      thank you, i think it could help.
      regards.

      Delete
  8. Great info! Its really great job for sharing this blog. Web Development Services India

    ReplyDelete
  9. It keeps giving me : HTTP Status 404 - /resources/test/kausal ...

    any idea why?

    ReplyDelete
    Replies
    1. HTTP status 404 error occurs when a resource is not available. Can you please check if the resource is available? Please note, all path names are case sensitive.

      You can also check tomcat logs to see what the error is.

      Delete
  10. Really helpful... I made only two changes to get it work in Spring Tool Suite (STS).

    i) updated the groupid with groupId and artifactid with artifactId


    com.sun.jersey
    jersey-server
    1.8


    ii) Updated the URL with RESTful/resources/test/James

    it works .. really nice and simple tutorial

    ReplyDelete
  11. Great article for beginners. Keep it up..Thanks for sharing Keep it up.
    Web Development Islamabad

    ReplyDelete
  12. Woow what a blog. You share here very nice information. Your blog is very nice. Keep share this type informative post. ..... marketing company

    ReplyDelete
  13. Thanks for the very informative blog

    Web Development Company in Jaipur,India. Richmind Softlabs is leading provider of website development and web services in Jaipur.


    so this post is very useful to us. Thank You...

    ReplyDelete
  14. Thanks for share this fantastic blog i like your work out i hope you will give us best knowledge in future thanks.Website Design Company Bangalore | Web Design Company Bangalore

    ReplyDelete
  15. Wow..its the awesome tips for me i have a search about java in more than blogs and websites but i have a getting the right information about java for your blog...thank you giving the useful information...
    Web Development Company Bangalore | Web Design Company Bangalore

    ReplyDelete
  16. Hi,

    Thanks for sharing a very interesting article about Developing a RESTful Java Web service in Eclipse Indigo using maven. This is very useful information for online blog review readers. Keep it up such a nice posting like this.

    From,
    Maestro Infotech,
    Web Design Company Bangalore

    ReplyDelete