REST services with Jersey and Spring 2.5

REST services are really useful : easy to write, easy to call and fast answers.

There are several implementations of JAX-RS (the Java 1.6 protocol for REST services):

  • Spring 3
  • RestEasy
  • Restlet
  • Jersey

And maybe more, but I don't know them all and the majors are there.

For this article, I've choosen to use Jersey, the Glassfish implementation of JAX-RS coupled with Spring 2.5.6 and Maven2 (Maybe in a later post I'll speak about the Spring 3 implementation).

This article describes 3 parts:

  1. Maven configuration
  2. web.xml and applicationContext.xml configuration
  3. Development of the webservice

The Maven Configuration

The pom.xml must include at least 2 frameworks : Spring and Jersey, but we will also add the Lombox plugin (to automatically generate the getters/setters, toString, … methods) and the JSON framework.

For this tutorial, I used Maven 2. I let you read the pom.xml file included in the sources package.

It contains the dependencies for Spring and Jersey, plus the dependencies for Lombok, JSon and Jetty.

The web.xml Configuration

The web.xml file has juste to describe 2 parts : the Spring config file and the redirection for the webservice:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="jersey">
 
    <display-name>jersey</display-name>
    <description>jersey</description>
 
    <!-- Spring configuration file -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
 
    <!-- Start Spring -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- REST Services -->
    <servlet>
        <servlet-name>Rest_Servlet</servlet-name>
        <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>Rest_Servlet</servlet-name>
        <!-- Redirect any calls to our jersey servlet -->
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
 
</web-app>

That's all for the web.xml file, nothing to do more :)

The applicationContext.xml Configuration

The applicationcontext.xml file just have to ask Spring to find itself the webservices and to instanciate the correct beans:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
 
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 
    <context:component-scan base-package="com.codeartex.jersey.web" />
 
    <!-- Bean WebService -->
    <bean id="wsTEst" class="com.codeartex.jersey.web.resources.WSTest"    autowire="byName" />
 
</beans>

A sample WebService

A Webservice is here just a new class and can encapsulate several services in one class :)

Each serv ice is just a method in this class. So it's very easy to add a new Webservice :)

The best practice is to add all the webservices of a same theme in the same class (i.e. a class for all the webservices for the users, a second class for all the webservices for the products, …)

Well, let's see how to declare this class with an example:

1
2
3
4
5
6
7
8
@Path("/test")
@Component          //tell Spring it&#39;s a component, so it will parse it at the start of the application
                    //(see the <context:component-scan base-package="com.codeartex.jersey.web" /> declaration in the applicationcontext.xml)
@Scope("singleton") //tell Spring it&#39;s a singleton, so instanciate it only one time
@Data               //Lombok annotation to generate automatically the getter/setter/toString/equals/hashcode methods
public class WSTest {
    //put here the methods...
}

A sample method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    /**
     * Webservice "hello" : return a string returning a "Hello {name}" String
     * @param name the name you want to show with the "Hello ..."
     *
     */
    @GET
    //the path to cal this webservice:
    //http://xx.xx.xx.xx:8080/test/hello/Gwen
    //{name} is the first parameter. You can add parameters
    @Path("hello/{name}")
    @Produces("text/plain")
    public String getMagasinById(@PathParam("name") String name) {
 
        StringBuffer buffer = new StringBuffer();
        buffer.append("Hello ").append(name);
 
        return buffer.toString();
    }

How to build and run the samples

To build the source with Maven, just run the following command:

mvn clean package

You can then execute it and test your webservices via Jetty (included in the pom.xml config file):

mvn jetty:run

Then, open a web browser window and enter the url:

http://localhost:8080/jersey/test/hello/YourName

Download

Click to download the sources of a full example

Glassfish V3 Installation on Linux (for beginners…)

Hi there,

sometimes we just need to intall a new server on a new virtual machine or at the start of a new project.

Here I wil just try to redefine the steps to install and configure a Glassfish V3 server on a Linux machine. Just afer that we will probably need to install a complete continuous platform of integration (with a Nexus or Archiva, a Hudson or continuum, Maven, Sonar, .., …) but it’s another subject. So maybe for a future post smiley

 

Well, let’s start by reminding what needs a Glassfish to run: a JDK.

In our case, we will first install a JDK6, so let’s begin with that.

 

1.Installation of the JDK6

1.1.Download

URL of the JDK 6 : http://java.sun.com/javase/downloads/index.jsp

The file should be called : « jdk-6u20-linux-i586-rpm.bin » (in the case of the version 20 of the JDK 6)

Juste paste the file in the directory /usr/java. If this directory does not exists, create it.

 

1.2.Installation

To install the JDK, move into the /usr/java directory and launch the following commands :

chmod 755 jdk-6u20-linux-i586-rpm.bin

./jdk-6-linux-i586-rpm.bin

that’s all :)

1.3.Verification

To check the correct installation of the JDK6, move into the /usr/java/jdk1.6.0_20 directory and launch :

/usr/java/jdk1.6.0_20/bin/java -version

You should see a message like this one:

 

java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02-279-10M3065)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01-279, mixed mode)

 

1.4.Variables

We will now export 2 variables which will point to the Java and Glassfish installation directory (Glassfish will be installed on the next chapter).

Open or create the etc/profile file.

Insert the following lines at the beginning of the file :

export JAVA_HOME=/usr/java/jdk1.6.0_20


export GLASSFISH_HOME=/usr/glassfishv3/glassfish


export PATH=$JAVA_HOME/bin:$GLASSFISH_HOME/bin:$PATH

 

1.5.update your profile

To immediately update our profile without having to disconnect and reconnect yourself, just enter the command :

source /etc/profile

 

2.Installation of Glassfish Server V3

Ok, now we are ready to install and use Glassfish, so we will first began by downloading the latest version.

2.1Download

URL of Glassfish V3 :

http://www.oracle.com/technetwork/java/javaee/downloads/ogs-3-1-1-downloads-439803.html

The direct URL : « http://download.java.net/glassfish/v3/release/glassfish-v3-unix.sh »

 

2.2Installation

On Linux (with a X environment) the installation is very easy and we just need to launch the setup (like in a Windows or MacOs world).

  • Create the destination directory by the following command : mkdir /usr/glassfishv3
  • move the installation file previously downloaded in the new directory
  • Launch the next line to start the installation :
    sh ./glassfish-v3-unix.sh

This last command will launch the installation wizard and will create a “glassfish” directory into the /usr/glassfishv3 directory.

Let the default values during the installation (only the installation directory and the admin password should be changed).

 

3.Deployment of an application (a WAR file) in Glassfish V3

You can deploy a WAR in Glassfish by several ways :

  • copy the WAR directly into the domain-dir/autodeploy/ directory (my be just in development environment, cause of the performance issues)
  • Use the Glassfish’ admin console
  • Use Ant script
  • Use asadmin script
  • Use an EDI (Eclipse, NetBeans, …)

3.1Deploy with the admin console

  • To launch the admin console, be first sure that the Glassfish server is running (/usr/glassfishv3/glassfish/bin/startserv).
    Then launch the web page at the following URL : http://localhost:4848
  • Open the node « Application ».
  • Clik on the « Deploy » button.
  • Select the option “Package file to be uploaded to the Application Server.”
  • Select thefull adress of the WAR file and then click on the OK button.
  • Click on Next.
  • Enter the name of the application.
  • Enter the Context-Root.
  • Select the checkbox “Enabled”.
  • Click on “End”.

 

3.2Deploy with asadmin

To deploy a WAR with asadmin, open a terminal and launch the command :

asadmin deploy full-path-to-war-file

 

3.3Deploy with Ant

 

To deploy a WAR with Ant, open a terminal on the directory containing the war file and launch the command :

ant deploy

 

4.Links

Here is where to download the needed files :

https://glassfish.dev.java.net/downloads/v3-final.html

http://java.sun.com/javaee/downloads/index.jsp

 

Here is the official documentation :

http://docs.sun.com/app/docs/doc/820-5968/ggssq?l=en&n=1&a=view

 

I hope this post could help at least someone :)

Feel free to ask me questions about the deployment or other questions related to the deployment and continuous integration.

Coming soon…

Coming soon:

  • A tutorial explaining how to use Jersey (Glassfih implementation of JAX-RS) with Spring and how it's really easy to implement :)
  • A tutorial demonstrating a sample application using spring, hibernate and ehcache.

Stay tuned :)