JAX-RS is a java specification which define APIs to implement RESTful web services. Jersey is a reference implementation of JAX-RS. It provides libraries to develop RESTful web services based on the JAX-RS specification. It uses a servlet to receive and dispatch client requests to right execution classes. In this tutorial, we will develop a simple service which returns string “Hello world!” to client using Jersey.
All needed tools are also provided in https://www-inf.telecom-sudparis.eu/~gaaloulw/Downloads.
package my.first.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("hello") //set your service url path to <base_url>/hello // the <base_url> is based on your application name, the servlet and the URL pattern from the web.xml configuration file public class Hello { // This method is called if TEXT_PLAIN is requested @GET @Produces(MediaType.TEXT_PLAIN) // defines which MIME type is delivered by a method annotated with @GET public String sayHelloInPlainText() { return "Hello world!"; } // This method is called if HTML is requested @GET @Produces(MediaType.TEXT_HTML) public String sayHelloInHtml() { return "<html> " + "<title>" + "Hello world!" + "</title>" + "<body><h1>" + "Hello world!" + "</body></h1>" + "</html> "; } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0"> <display-name>rest</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>jersey-servlet</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>my.first.rest</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>