Tổng Hợp

Java RESTful Web Services Tutorial for Beginner with Jersey and Tomcat

Java RESTful Website Services Tutorial for Beginner with Jersey and Tomcat

RESTful Website Services is a programming model based on REST (Representational State Transfer) architecture, which makes use of standard HTTP methods (GET, POST, PUT, DELETE…) to manipulate resources identified by URIs, and JSON/XML to exchange data between servers and clients. RESTful website services is commonly used to develop APIs for web-based applications because of its simplicity, lightweight, performance, reliability and scalability.In this tutorial, I will help you get started with RESTful website services in Java by developing a Java website application running on Apache Tomcat server – this website application hosts Restful website services powered by

1. Create Project and Specify Jersey Dependency

In Eclipse IDE, create a Dynamic Java Website project named as HelloREST. And convert it to Maven project by right clicking on the project, click Configure > Convert to Maven project. Open the

pom.xml

file and declare the following dependency:

<dependenciesvàgt;
	<dependencyvàgt;
		<groupIdvàgt;org.glassfish.jersey.containersvàlt;/groupIdvàgt;
		<artifactIdvàgt;jersey-container-servletvàlt;/artifactIdvàgt;
		<versionvàgt;2.25.1vàlt;/versionvàgt;
	</dependencyvàgt;
</dependenciesvàgt;

This dependency is required to develop RESTful website services in Java, using Jersey framework – an implementation of Java API for RESTful Website Services (JAX-RS).Use the version 2.25.x if your Tomcat running on JDK 8. In case you use JDK 11 or later, you should use newer version, e.g. Jersey 2.29.1 like this:

<dependencyvàgt;
	<groupIdvàgt;org.glassfish.jersey.containersvàlt;/groupIdvàgt;
	<artifactIdvàgt;jersey-container-servletvàlt;/artifactIdvàgt;
	<versionvàgt;2.29.1vàlt;/versionvàgt;
</dependencyvàgt;
<dependencyvàgt;
	<groupIdvàgt;org.glassfish.jersey.injectvàlt;/groupIdvàgt;
	<artifactIdvàgt;jersey-hk2vàlt;/artifactIdvàgt;
	<versionvàgt;2.29.1vàlt;/versionvàgt;
</dependencyvàgt;

For Jersey 2.26.x or newer, you must also declare the Jersey Inject dependency as shown above. So let use the Jersey version 2.29.1 because it works well both on JDK 8 and recent JDK versions (JDK 11 or newer).

2. Code a Hello World RESTful Website Service

Create a new class

Hello

under the package

net.codejava

with the following code:

package net.codejava;


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

@Path("/bonjour")
public class HelloResource {

	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public String direBonjour() {
		return "Bonjour, tout le monde!";
	}
}

Look, this is your first class for RESTful website services. Let me explain:The

@Path

annotation defines the relative URL that forms the URI that identifies a resource. You can use this annotation on both class level or method level.The

@GET

annotation specifies that the annotated method,

direBonjour()

handles HTTP GET request. Jersey provides annotations corresponding to HTTP methods:

@POST

,

@PUT

,

@DELETE

…The

@Produces

annotation specifies the content type of the response, which is text plain in our code. You can also specify text/xml, text/html, JSON, etc.And you can see the method

direBonjour()

returns a plain text, saying hello world in French – as response to the clients.

3. Configure Jersey Servlet Container

Next, we need configure Jersey servlet in the website deployment descriptor (website.xml) file like this:

<servletvàgt;
	<servlet-namevàgt;Jersey REST Servicevàlt;/servlet-namevàgt;
	<servlet-classvàgt;org.glassfish.jersey.servlet.ServletContainervàlt;/servlet-classvàgt;
	<init-paramvàgt;
		<param-namevàgt;jersey.config.server.provider.packagesvàlt;/param-namevàgt;
		<param-valuevàgt;net.codejavavàlt;/param-valuevàgt;
	</init-paramvàgt;
	<load-on-startupvàgt;1vàlt;/load-on-startupvàgt;
</servletvàgt;

<servlet-mappingvàgt;
	<servlet-namevàgt;Jersey REST Servicevàlt;/servlet-namevàgt;
	<url-patternvàgt;/rest/*</url-patternvàgt;
</servlet-mappingvàgt;

Note that we need to specify the package name that contains the classes that need to be exposed as RESTful website services, as an initialization parameter of Jersey servlet; and the URL pattern will be handled by Jersey servlet container.Now, you can

4. Test RESTful Website Service using website browser

Open a website browser (e.g. Chrome) and type the following URL:

RESTful Website Services is a programming model based on REST (Representational State Transfer) architecture, which makes use of standard HTTP methods (GET, POST, PUT, DELETE…) to manipulate resources identified by URIs, and JSON/XML to exchange data between servers and clients. RESTful website services is commonly used to develop APIs for web-based applications because of its simplicity, lightweight, performance, reliability and scalability.In this tutorial, I will help you get started with RESTful website services in Java by developing a Java website application running on Apache Tomcat server – this website application hosts Restful website services powered by Jersey – an open source framework for developing RESTful website services in Java. Jersey is a reference implementation of JAX-RS (Java API for RESTful Website Services).You will also learn to test RESTful website services using cURL and Postman tools, and code a RESTful website services client program using Jersey client API.To follow this tutorial, you should be familiar with website development in Java with Eclipse IDE, Apache Tomcat server and Maven.In Eclipse IDE, create a Dynamic Java Website project named as. And convert it to Maven project by right clicking on the project, click. Open thefile and declare the following dependency:This dependency is required to develop RESTful website services in Java, using Jersey framework – an implementation of Java API for RESTful Website Services (JAX-RS).Use the version 2.25.x if your Tomcat running on JDK 8. In case you use JDK 11 or later, you should use newer version, e.g. Jersey 2.29.1 like this:For Jersey 2.26.x or newer, you must also declare the Jersey Inject dependency as shown above. So let use the Jersey version 2.29.1 because it works well both on JDK 8 and recent JDK versions (JDK 11 or newer).Create a new classunder the packagewith the following code:Look, this is your first class for RESTful website services. Let me explain:Theannotation defines the relative URL that forms the URI that identifies a resource. You can use this annotation on both class level or method level.Theannotation specifies that the annotated method,handles HTTP GET request. Jersey provides annotations corresponding to HTTP methods:…Theannotation specifies the content type of the response, which is text plain in our code. You can also specify text/xml, text/html, JSON, etc.And you can see the methodreturns a plain text, saying hello world in French – as response to the clients.Next, we need configure Jersey servlet in the website deployment descriptor (website.xml) file like this:Note that we need to specify the package name that contains the classes that need to be exposed as RESTful website services, as an initialization parameter of Jersey servlet; and the URL pattern will be handled by Jersey servlet container.Now, you can add this project to Tomcat and start the server to test the website service.Open a website browser (e.g. Chrome) and type the following URL:

Then you should see the following page:RESTful test in chrome plain textYou see, the browser displays the plain text response sent by the website service. Now, add second method to the

HelloResource

 

class:

@GET
@Produces(MediaType.TEXT_HTML)
public String sayHTMLHello() {
	return "<html><title>Hello</title><body><h1>Bonjour, tout le monde!</h1><body></html>";
}

This method returns a HTML response. Refresh the browser and you should see:RESTful test in chrome htmlYou see, the browser now shows the HTML response sent from the website service (a website browser always expects Text/HTML response). That means with the same URI, the response representation can be different, depending on content type accepted by the clients. 

5. Using JSON for RESTful website services

JSON is a preferred format for data representation in RESTful website services because of its simplicity and lightweight.To use JSON with Jersey, you need to add the following dependency to the pom.xml file:

<dependencyvàgt;
	<groupIdvàgt;org.glassfish.jersey.mediavàlt;/groupIdvàgt;
	<artifactIdvàgt;jersey-media-json-jacksonvàlt;/artifactIdvàgt;
	<versionvàgt;2.29.1vàlt;/versionvàgt;
</dependencyvàgt;

Now, update the

HelloResource

 

class to have a new method that produces JSON response, as follows:

@GET
@Produces(MediaType.APPLICATION_JSON)
public String sayJsonHello() {
	return "{"name":"greeting", "message":"Bonjour tout le monde!"}";
}

This method returns a simple piece JSON data. If you refresh the browser, you will see nothing changes because the browser doesn’t expect JSON response by default. 

6. Test RESTful Website Service using curl

curl is a command-line tool which is widely used to test RESTful website services APIs. If you’re using Windows 10, curl is shipped with the operating system by default. If not, you can

Then you should see the following page:You see, the browser displays the plain text response sent by the website service. Now, add second method to theclass:This method returns a HTML response. Refresh the browser and you should see:You see, the browser now shows the HTML response sent from the website service (a website browser always expects Text/HTML response). That means with the same URI, the response representation can be different, depending on content type accepted by the clients.JSON is a preferred format for data representation in RESTful website services because of its simplicity and lightweight.To use JSON with Jersey, you need to add the following dependency to the pom.xml file:Now, update theclass to have a new method that produces JSON response, as follows:This method returns a simple piece JSON data. If you refresh the browser, you will see nothing changes because the browser doesn’t expect JSON response by default.is a command-line tool which is widely used to test RESTful website services APIs. If you’re using Windows 10, curl is shipped with the operating system by default. If not, you can download curl here .Type the following command to test our website service:

Then you can see JSON response:

{"name":"greeting", "message":"Bonjour tout le monde!"}

You can use the –v option (versbose) to see more details such as request headers and response headers. For example:

Then you can see JSON response:You can use the –v option (versbose) to see more details such as request headers and response headers. For example:

Then you can see the output something like this:curl verbose test web serviceYou can use the –H option to specify a HTTP header in the request. For example:

Then you can see the output something like this:You can use the –H option to specify a HTTP header in the request. For example:

curl -H “Accept: text/html” http://localhost:8080/HelloREST/rest/bonjour

This command tells the server that the client expects response format to be of text/html. Hence the following response:

<htmlvàgt;<titlevàgt;Hellovàlt;/titlevàgt;<bodyvàgt;<h1vàgt;Bonjour, tout le monde!</h1vàgt;<bodyvàgt;</htmlvàgt;

And the following curl command will get plain text response from the server:

This command tells the server that the client expects response format to be of text/html. Hence the following response:And the following curl command will get plain text response from the server:

curl -H “Accept: text/plain” http://localhost:8080/HelloREST/rest/bonjour

7. Test RESTful Website Service using Postman

Postman is a GUI tool that can be used to test website service APIs. test webservice postmanAs you can see, Postman is easier to use and more advanced than curl. 

8. Code a RESTful Website Service Client program

You can use Jersey Client API to write client programs that consume RESTful website services. Create a new Maven project, e.g. 

HelloClient

 

and add the following dependencies to the 

pom.xml

 file:

<dependencyvàgt;
	<groupIdvàgt;org.glassfish.jersey.corevàlt;/groupIdvàgt;
	<artifactIdvàgt;jersey-clientvàlt;/artifactIdvàgt;
	<versionvàgt;2.29.1vàlt;/versionvàgt;
</dependencyvàgt;
<dependencyvàgt;
	<groupIdvàgt;org.glassfish.jersey.injectvàlt;/groupIdvàgt;
	<artifactIdvàgt;jersey-hk2vàlt;/artifactIdvàgt;
	<versionvàgt;2.29.1vàlt;/versionvàgt;
</dependencyvàgt;

Then code a simple RESTful website service client program as follows:

package net.codejava;

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

import org.glassfish.jersey.client.ClientConfig;


public class HelloClient {

	public static void main(String[] args) {
		String uri = "http://localhost:8080/HelloREST/rest/bonjour";
		ClientConfig config = new ClientConfig();
		Client client = ClientBuilder.newClient(config);
		WebTarget target = client.target(uri);
		
		String response = target.request()
					.accept(MediaType.APPLICATION_JSON)
					.get(String.class);
		
		System.out.println(response);

	}

}

This program simply sends a GET request to the server at the specified URI and reads the response. Run this program and you should see the following output:

Postman is a GUI tool that can be used to test website service APIs. Click here download and install Postman on your computer (you have to create an tài khoản to use – free). Then create a new collection and a request under this collection. Then type a URL and click Send, as shown below:As you can see, Postman is easier to use and more advanced than curl.You can use Jersey Client API to write client programs that consume RESTful website services. Create a new Maven project, e.g.and add the following dependencies to thefile:Then code a simple RESTful website service client program as follows:This program simply sends a GET request to the server at the specified URI and reads the response. Run this program and you should see the following output:

{“name”:”greeting”, “message”:”Bonjour tout le monde!”}

This is JSON response because the client expects application/json as the accepted media type.Congratulations, you have done your first hello world RESTful website services application, with both server and client. For your reference, you can download the sample project in the attachments section below.You can also watch the video version of this tutorial below:

 

Other Java Website Services Tutorial:

About the tác giả:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Fb and watch his Java videos you YouTube.

Attachments:JavaRESTfulBeginner.zip[RESTful client server project]20 kB

Add comment

This is JSON response because the client expects application/json as the accepted media type.Congratulations, you have done your first hello world RESTful website services application, with both server and client. For your reference, you can download the sample project in the attachments section below.You can also watch the video version of this tutorial below:

Xem thêm bài viết thuộc chuyên mục: Kĩ Năng Sống

Xem Thêm :   8 cách làm trắng da toàn thân tại nhà nhanh chóng

Xem thêm bài viết thuộc chuyên mục: Tổng Hợp
Xem thêm :  Xem Phim Vượt Ngục (Phần 1) Tập 16 (HD,THUYẾT MINH ,VIETSUB)

Related Articles

Back to top button