The first step for creating a new project is to accumulate the required tools:
Java JDK (Version 6 or higher)
Eclipse IDE (Juno)
Apache Tomcat Server (Version 7) or Glassfish Server (Version 4.0)
Jersey Framework
Firstly, we will create a web project using Eclipse IDE. Go to File | New | Others | Dynamic Web Project. Follow the steps, and after the project is created, add the following libraries into the classpath:
asm-all-repackaged-2.2.0-b14.jar
cglib-2.2.0-b14.jar
guava-14.0.1.jar
hk2-api-2.2.0-b14.jar
hk2-locator-2.2.0-b14.jar
hk2-utils-2.2.0-b14.jar
javax.annotation-api-1.2.jar
javax.inject-2.2.0-b14.jar
javax.ws.rs-api-2.0.jar
jersey-client-2.2.jar
jersey-common-2.2.jar
jersey-container-servlet-core-2.2.jar
jersey-server-2.2.jar
osgi-resource-locator-1.0.1.jar
validation-api-1.1.0.Final.jar
Now, we need to configure web.xml
to the bound Jersey Container with the resources packages:
........... <servlet> <servlet-name>simpleJerseyExample</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>com.demo</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>simpleJerseyExample</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> ...........
A servlet container is treated as a controller to redirect the specified resource that is being called. jersey.config.server.provider.packages
maps the resources that are available in the com.demo
package. So, whenever any resource is being requested, ServletContainer
checks into the com.demo
package for the resource URI and serves the request accordingly.
The next step is to create the
Resource
class that contains the business logic:
package com.demo; import javax.ws.rs.Path; import javax.ws.rs.Get; import javax.ws.rs.core.MediaType; import javax.ws.rs.Produces; /** * helloWorld Root Resource */ @Path("helloWorld") public class HelloWorldResource{ @GET @PRODUCES(MediaType.TEXT_PLAIN) public String greet(){ return "Hello World!!!"; } }
Tip
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
A JAX-RS resource is an annotated POJO, which provides the so-called resource methods that are able to handle the HTTP requests for the URI paths bound to the resource. In the previous code, "helloWorld"
is the resource URI:
@Path("helloWorld")
To run the application, create a WAR file and deploy it on the Apache Tomcat Server. Once the project is deployed on the Tomcat server, we are ready to consume the "helloWorld" web service. We can type the resource URL in the browser or we can use curl
:
$curl http://localhost:8080/projectName/services/helloWorld Hello World!!!