Sunday, November 25, 2012

Jx-RS and Maven

In this topic I am going to create a java web service application using jx-rs and maven.

  • So first of all we are going to create a Maven web project.
  • Go to this Link For Project Creation: Create Maven Base Web Project.
  • Open pom.xml file add dependencies. Dependencies mean the jars file that project need. For example we need blow jars for our project.

  1. commons-lang-2.3.jar 
  2. jaxb-api-2.1.jar
  3. jaxb-impl-2.1.4.jar
  4. stax-api-1.0-2.jar
  5. jsr311-api-1.1.jar
  6. slf4j-api-1.5.11.jar
  7. slf4j-jdk-1.5.11.jar
  8. wink-common-<version #>.jar
  9. wink-server-<version #>.jar

  • Instead of adding these jars in project and updating with change inversions, we are using maven which will do this work for us on chnage in pom.xml
  • We need few plugins for maven as well to run this project on Apache tomcat
  • So pom file is here pom.xml.
  • Now go to src/main/webapp/WEB_INF/web.xml
  • Add internal servlet and servlet mapping for jx-rs.
  • Register the web service with
  • I am making a file which is extending is registering our service class MainServices.clas with rest servlet 

  • Now write a web service in java file. My service file name is
  • @Path("/mainServices") annotation on top of  Class MainServices is the path to this web service from the Rest servlet (servlet declare in web.xml). 
  • This thing means this /mainServices will append with path of Rest Servlet which is (/service/ => in web.xml).
  • @GET @Path("/hellow_world" )  @Produces(MediaType.APPLICATION_JSON)
 public String helloWorld(){}
  • Method helloWorld() is working as separate service and its path on url is /hellow_world. And this path is append with the path of Class MainServices "/mainServices".
  • So path to this service is    "BASER_URL + /service/mainServices/hellow_world"
  • @GET means the method to access this service is GET.
  • @Produces(MediaType.APPLICATION_JSON) means this is service is returning json.

  • No take a look on a web service (/user_details) which is getting the data from html forms and methods we are using is post.

  • It is consuming (taking input) the form data   Content Type = application/x-www-form-urlencoded
  • @FormParam("userName") String name. The annotation @FormParam is mapping  html form  field = userName to Java variable name.
  • You can access the web service with the blow url http://localhost:8080/

You can get source code from this link Source Code