Jersey integration with Spring(Restful web service)

Restful Web service Introduction:
REST-style architectures consist of clients and servers. Clients initiate requests to servers; servers process requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources. A resource can be essentially any coherent and meaningful concept that may be addressed. A representation of a resource is typically a document that captures the current or intended state of a resource.

Jersey
Jersey  is an open-source, production-ready reference implementation of JAX-RS, the Java API for RESTful Web Services (JSR-311). Jersey makes it easy to create RESTful web services using Java technology.

Building a Small “Ping” restful webservice

Step 1:
Jersey resource:
A Jersey resource is a plain Java class within the context of a web application that uses the @Path annotation to define a URI. The URI represent the relative path to the web context of the deployed app.

@Path(“/pingservice”)
public class SayPingResource{
private String param1;

@GET
@Produces(“application/plain“)
public String getMessage() {
// logic placeholder
return this.param1;
}

public void setParam1(String param){
this.param1=param;
}
@Path: This defines the base URI. Formed with context root and hostname, the resource identifier will be something like
http://localhost:8080/mysampleapp/service/pingservice
@GET: This means that the following method responds to the HTTP GET method.
@Produces: Defines the response content MIME type as plain/text.

Integration With Spring
Step 2:
Define Jersey Spring servlet in Web.xml

 <servlet>
<servlet-name>Jersey Spring</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Jersey Spring</servlet-name>
<url-pattern>/\*</url-pattern>
</servlet-mapping>

Step 3:
Now inside application.xml add the bean declaration for the Restful service

<beans>
<bean id=”pingbean”  class=”com.test.SayPingResource”>
<property name=”param1″ value=”Success Response”/>
</bean>
</beans>

Once the above changes are done, restart/deploy the application. And access with below URI.

http://localhost:8080/mysampleapp/service/pingservice

Output : “Success Response”

This is my first hands on with Jersey + Spring, Your comments would help me gearing up to write more post on the same 🙂


Thanks
R Vashi

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s