Thursday, January 7, 2016

Implementing a JAX-RS webservice with Jersey

In this tutorial we’ll create a JAX-RS webservice with the Jersey implementation. The Jersey is the best choice, if you have an older JBoss instance. But, if you have a JBoss 6.1, 7.1, EAP 6+, you should use RestEasy or Apache CXF.


Let’s create a Maven based web project(maven-webapp archetype). This is not the place of discussing it, I hope you have the skill to do it. If you did it, open the projects pom.xml file, and edit the <dependencies> part. Add the following dependency:


<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>


This is the server side API of the Jersey JAX-RS implementation. Additionally, we have to set the Jersey’s custom remote repository, to do this, paste the upcoming lines into your pom.xml:


<repositories>
<repository>
<id>maven2-repository.java.net</id>
<name>Java.net Repository for Maven</name>
<url>http://download.java.net/maven/2/</url>
<layout>default</layout>
</repository>
</repositories>


Ok, we set up successfully our Maven project, now we’ll create a REST interface called HelloWorldWS. The name of the class is not important, because the path will be set by annotations:


package hu.developertutorials.java.jersey;


import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;


@Path("/hello")
public class HelloWorldWS {
@GET
@Path("/{param}")
public Response getMsg(@PathParam("param") String msg) {
String output = "Jersey say : " + msg;
return Response.status(200).entity(output).build();
}
}


The last item of the TODO list is to set up correctly the web.xml file.

<web-app id="WebApp_ID" version="2.5"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd">
<display-name>DeveloperTutorials Sample JAX-RS webapplication</display-name>
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>
                    com.sun.jersey.spi.container.servlet.ServletContainer
               </servlet-class>
<init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>hu.developertutorials.java.jersey</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

</web-app>

Configure and use VSCode for Java web development

Embarking on Java web development often starts with choosing the right tools that streamline the coding process while enhancing productivity...