Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes

9
Build Your First Java Jersey JAX-RS REST Web Service Project in less than 15 Minutes. For this tutorial, you need these tools properly installed: Jdk 8; Tomcat 7; Eclipse Mars with Tomcat Plugin and Web/J2EE Plugins; and Jersey 2. I am doing this tutorial in my Windows 10 laptop and here are the detail steps: 1. Launch Eclipse. Click File, New, Other, and start to type Dynamic on top text field, you will see “Dynamic Web Project” showing up under Web as shown here: Click Dynamic Web Project and press Next button. In the next Window, give project name as RestWSProject and press Next button. When you see a window showing a checkbox “Generate web.xml deployment descriptor”,

Transcript of Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes

Page 1: Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes

Build Your First Java Jersey JAX-RS REST Web Service Project in less than 15 Minutes.

For this tutorial, you need these tools properly installed: Jdk 8; Tomcat 7; Eclipse Mars with Tomcat Plugin and Web/J2EE Plugins; and Jersey 2. I am doing this tutorial in my Windows 10 laptop and here are the detail steps:

1. Launch Eclipse. Click File, New, Other, and start to type Dynamic on top text field, you will see “Dynamic Web Project” showing up under Web as shown here:

Click Dynamic Web Project and press Next button. In the next Window, give project name as RestWSProject and press Next button. When you see a window showing a checkbox “Generate web.xml deployment descriptor”, you need to make sure to check “Generate web.xml deployment descriptor” checkbox before pressing Finish button.

2. Copy all jar files under Jersey lib, ext, and api subfolders to a single folder WebContent\WEB-INF\lib folder.

3. Create HelloWorldService.java:

Page 2: Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes

package com.webservice.rest;

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

@Path("/hello")public class HelloWorldService {

// on browser, you need to type like:// http://localhost:8080/RestWSProject/rest/hello// The page will show:// Jersey says: Hi there!@GETpublic Response getGreetings() {

String message = "Jersey says: Hi there!";System.out.println("getGreetings(): " + message);return Response.status(200).entity(message).build();

}

// on browser, you need to type like:// http://localhost:8080/RestWSProject/rest/hello/Robert// The page will show:// Jersey says: Hi Robert, How are you?@GET@Path("/{param}")public Response getGreetingsToName(@PathParam("param") String name) {

String message = "Jersey says: Hi " + name + ", How are you?";System.out.println("getGreetingsToName(): " + message);return Response.status(200).entity(message).build();

}

// on browser, you need to type like:// http://localhost:8080/RestWSProject/rest/hello/plain// The page will show:// Jersey says: Hello World!@Path("/plain")@GET@Produces(MediaType.TEXT_PLAIN)public String getGreetingToTheWorldByPlain() {

String message = "Jersey says: Hello World in Plain Text!";System.out.println("getGreetingToTheWorldByPlain(): " + message);return message;

}

// on browser, you need to type like:// http://localhost:8080/RestWSProject/rest/hello/html@Path("/html")@GET@Produces(MediaType.TEXT_HTML)public String getGreetingToTheWorldByHtml() {

String message = "Jersey says: Hello World in HTML!";String output = "<html lang=\"en\"><body><h1>" + message +

"</body></h1></html>";

Page 3: Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes

System.out.println("getGreetingToTheWorldByHtml(): " + output);return output;

}

// on browser, you need to type like:// http://localhost:8080/RestWSProject/rest/hello/xml@Path("/xml")@GET@Produces(MediaType.TEXT_XML)public String getGreetingToTheWorldByXml() {

String message = "Jersey says: Hello World in XML!";String output = "<?xml version=\"1.0\"?>" + "<hello>" + message +

"</hello>";System.out.println("getGreetingToTheWorldByXml(): " + output);return output;

}}

4. Create a Java web service client HelloWorldServiceDemoMain.java as the following:

package com.webservice.rest;

import javax.ws.rs.client.ClientBuilder;import javax.ws.rs.client.WebTarget;import javax.ws.rs.core.MediaType;import javax.ws.rs.core.Response;

public class HelloWorldServiceDemoMain {

public static void main(String[] args) {WebTarget target =

ClientBuilder.newClient().target("http://localhost:8080/RestWSProject/rest/hello");

String response = target.request().accept(MediaType.TEXT_PLAIN).get(Response.class)

.toString();String responseToMe =

target.path("Robert").request().accept(MediaType.TEXT_PLAIN).get(Response.class).toString();

String plainAnswer = target.path("plain").request().accept(MediaType.TEXT_PLAIN)

.get(String.class);String xmlAnswer =

target.path("xml").request().accept(MediaType.TEXT_XML).get(String.class);

String htmlAnswer = target.path("html").request().accept(MediaType.TEXT_HTML)

.get(String.class);System.out.println(response);System.out.println(responseToMe);System.out.println(plainAnswer);System.out.println(xmlAnswer);System.out.println(htmlAnswer);

}}

Page 4: Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes

5. Make sure the web.xml file under WebContent\WEB-INF has the content as this:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID" version="3.0"><display-name>RestWSProject</display-name><welcome-file-list>

<welcome-file>index.html</welcome-file></welcome-file-list><servlet>

<servlet-name>HelloWorld</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.webservice.rest</param-value></init-param><load-on-startup>1</load-on-startup>

</servlet><servlet-mapping>

<servlet-name>HelloWorld</servlet-name><url-pattern>/rest/*</url-pattern>

</servlet-mapping></web-app>

6. Create index.html file under WebContent like this:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body>Tomcat runs perfect!</body></html>

The final project structure looks like this:

Page 5: Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes

7. Right click the project name on Project Explorer panel of Eclipse, choose Run AS and then Run on Server. On the next Add and Remove window, click the project name of RestWSProject on the left side Available column, press Add button in the middle, and you will see the project is added to Tomcat server as it is shown in the Configured column on right side:

Page 6: Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes

Click Finish button.

The project is deployed and after a few seconds the server is started and Eclipse opens a browser window itself showing the default index.html page. The default URL is http://localhost:8080/RestWSProject/ and the page is showing as this:

Page 7: Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes

This is because the web.xml has a single welcome-file of index.html page inside the element of welcome-file-list.

8. You can change the URL to see all different page contents by using different path corresponding to the @Path annotation defined inside the HelloWorldService.java file where each method has detailed explanation.

For example, type URL of http://localhost:8080/RestWSProject/rest/hello/ you will see the page showing:

Type URL of http://localhost:8080/RestWSProject/rest/hello/Robert you will see the page showing:

And finally type URL of http://localhost:8080/RestWSProject/rest/hello/xml you will see the page showing:

Here are a couple of things to note as how the URL is built:

First of all, we know we are starting our Tomcat server in localhost and the port 8080. Thus it’s http://localhost:8080.

Next, it’s the context root. Right click the project on Project Explorer panel of Eclipse, choose Properties, and click Web Project Settings, you will see the Context Root has the value of “RestWSProject” which is basically the project name, so we get http://localhost:8080/RestWSProject.

Check the web.xml file, we know we have a servlet mapping as <url-pattern>/rest/*</url-pattern>, therefore, we come to URL of http://localhost:8080/RestWSProject/rest.

Finally let’s check how the path is created inside the HelloWorldService.java file. At the class level, we have an annotation of @Path(“/hello”). So if a method has no @Path annotation (such as the first method getGreetings() the full URL path will be http://localhost:8080/RestWSProject/rest/hello. If there is a path annotation at a method level such as

Page 8: Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes

getGreetingsToName() with @Path("/{param}"), then it’s a parameter and the URL will be http://localhost:8080/RestWSProject/rest/hello/Robert while knowing the last part of this URL (That’s “Robert”) will be a parameter used by the method. Another scenario is the method of getGreetingToTheWorldByPlain() which has a path annotation associated with it called @Path("/plain"). This actually creates a URL of http://localhost:8080/RestWSProject/rest/hello/plain. So basically, the REST web service path and thus its URL is a result of combination of class level path and method level path using JAX-RS path annotation.

and any further path

9. Finally, the HelloWorldServiceDemoMain.java is a Java web service client which invokes the REST web service methods programmatically. Right click this class, choose Run As and then Run Application, you will see the results printed in the console:

Page 9: Build Your First Java Jersey JAX-RS REST Web Service in less than 15 Minutes

Congratulations! You successfully completed your first REST web service in no time!