How To Deploy Restful Web Service In Tomcat
- Details
- Written by
- Last Updated on 21 December 2019 | Print E-mail
RESTful Spider web Services is a programming model based on Residue (Representational State Transfer) architecture, which makes use of standard HTTP methods (Go, POST, PUT, DELETE…) to manipulate resource identified by URIs, and JSON/XML to exchange data betwixt servers and clients. RESTful web services is ordinarily used to develop APIs for spider web-based applications because of its simplicity, lightweight, functioning, reliability and scalability.
In this tutorial, I will help yous get started with RESTful web services in Java by developing a Java web application running on Apache Tomcat server – this web application hosts Restful web services powered by Jersey – an open source framework for developing RESTful web services in Coffee. Bailiwick of jersey is a reference implementation of JAX-RS (Java API for RESTful Web Services).
You will besides larn to exam RESTful web services using cURL and Postman tools, and code a RESTful web services client program using Bailiwick of jersey client API.
To follow this tutorial, y'all should be familiar with web development in Java with Eclipse IDE, Apache Tomcat server and Maven.
i. Create Projection and Specify Jersey Dependency
In Eclipse IDE, create a Dynamic Java Spider web project named as HelloREST. And convert it to Maven projection by right clicking on the project, click Configure > Catechumen to Maven project. Open the pom.xml file and declare the following dependency:
<dependencies> <dependency> <groupId>org.glassfish.bailiwick of jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId> <version>ii.25.ane</version> </dependency> </dependencies>
This dependency is required to develop RESTful web services in Java, using Bailiwick of jersey framework – an implementation of Java API for RESTful Spider web Services (JAX-RS).
Apply the version two.25.x if your Tomcat running on JDK 8. In instance y'all use JDK 11 or later, you should utilise newer version, eastward.chiliad. Jersey two.29.1 like this:
<dependency> <groupId>org.glassfish.bailiwick of jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId> <version>ii.29.ane</version> </dependency> <dependency> <groupId>org.glassfish.jersey.inject</groupId> <artifactId>jersey-hk2</artifactId> <version>2.29.1</version> </dependency>
For Jersey 2.26.x or newer, y'all must too declare the Bailiwick of jersey Inject dependency every bit shown above. And then let use the Jersey version 2.29.1 because it works well both on JDK 8 and recent JDK versions (JDK xi or newer).
two. Lawmaking a Hello Earth RESTful Spider web Service
Create a new class Hello under the package cyberspace.codejava with the following code:
parcel net.codejava; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.cadre.MediaType; @Path("/bonjour") public class HelloResource { @GET @Produces(MediaType.TEXT_PLAIN) public Cord direBonjour() { return "Bonjour, tout le monde!"; } }
Look, this is your beginning class for RESTful web services. Let me explain:
The @Path annotation defines the relative URL that forms the URI that identifies a resource. You tin utilise 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 likewise specify text/xml, text/html, JSON, etc.
And you can run into the method direBonjour() returns a apparently text, saying hello world in French – every bit response to the clients.
3. Configure Jersey Servlet Container
Next, nosotros need configure Jersey servlet in the web deployment descriptor (web.xml) file like this:
<servlet> <servlet-name>Jersey Residuum Service</servlet-name> <servlet-grade>org.glassfish.jersey.servlet.ServletContainer</servlet-form> <init-param> <param-name>jersey.config.server.provider.packages</param-proper name> <param-value>net.codejava</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/rest/*</url-blueprint> </servlet-mapping>
Note that we need to specify the package name that contains the classes that need to be exposed every bit RESTful web services, as an initialization parameter of Jersey servlet; and the URL pattern will be handled by Jersey servlet container.
Now, y'all tin can add this project to Tomcat and get-go the server to test the web service.
4. Test RESTful Web Service using spider web browser
Open a web browser (e.g. Chrome) and blazon the post-obit URL:
http://localhost:8080/HelloREST/rest/bonjour
Then you should see the following page:
Y'all run into, the browser displays the plain text response sent by the web service. At present, add second method to the HelloResourceform:
@GET @Produces(MediaType.TEXT_HTML) public String sayHTMLHello() { render "<html><title>Hi</title><torso><h1>Bonjour, tout le monde!</h1><torso></html>"; }
This method returns a HTML response. Refresh the browser and you should see:
You lot see, the browser now shows the HTML response sent from the web service (a web browser always expects Text/HTML response). That means with the aforementioned URI, the response representation can be dissimilar, depending on content type accustomed past the clients.
5. Using JSON for RESTful spider web services
JSON is a preferred format for information representation in RESTful spider web services because of its simplicity and lightweight.
To utilise JSON with Jersey, you lot need to add together the following dependency to the pom.xml file:
<dependency> <groupId>org.glassfish.jersey.media</groupId> <artifactId>bailiwick of jersey-media-json-jackson</artifactId> <version>2.29.ane</version> </dependency>
Now, update the HelloResourceclass to have a new method that produces JSON response, as follows:
@Go @Produces(MediaType.APPLICATION_JSON) public String sayJsonHello() { render "{\"name\":\"greeting\", \"message\":\"Bonjour tout le monde!\"}"; }
This method returns a elementary piece JSON data. If you refresh the browser, you will see nothing changes because the browser doesn't expect JSON response past default.
6. Test RESTful Web Service using curlicue
curl is a command-line tool which is widely used to test RESTful spider web services APIs. If you're using Windows 10, curl is shipped with the operating system by default. If non, you tin can download curl here.
Type the post-obit command to test our spider web service:
curl http://localhost:8080/HelloREST/balance/bonjour
And then you tin can see JSON response:
{"name":"greeting", "message":"Bonjour tout le monde!"}
You can employ the –5 option (versbose) to run across more than details such as request headers and response headers. For example:
ringlet -v http://localhost:8080/HelloREST/rest/bonjour
Then you can see the output something like this:
You tin 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 exist of text/html. Hence the following response:
<html><title>Hello</title><body><h1>Bonjour, tout le monde!</h1><body></html>
And the following scroll command will get plainly text response from the server:
curl -H "Accept: text/plain" http://localhost:8080/HelloREST/residuum/bonjour
7. Test RESTful Web Service using Postman
Postman is a GUI tool that can be used to exam spider web service APIs. Click hither download and install Postman on your computer (yous have to create an account to use – gratis). Then create a new collection and a request under this drove. Then blazon a URL and click Transport, as shown below:
As yous tin see, Postman is easier to use and more advanced than ringlet.
8. Code a RESTful Spider web Service Client program
You can use Bailiwick of jersey Client API to write client programs that eat RESTful web services. Create a new Maven projection, e.g. HelloClientand add the following dependencies to thepom.xml file:
<dependency> <groupId>org.glassfish.jersey.cadre</groupId> <artifactId>jersey-client</artifactId> <version>2.29.1</version> </dependency> <dependency> <groupId>org.glassfish.bailiwick of jersey.inject</groupId> <artifactId>jersey-hk2</artifactId> <version>2.29.1</version> </dependency>
Then lawmaking a uncomplicated RESTful web service client plan equally follows:
bundle cyberspace.codejava; import javax.ws.rs.client.Client; import javax.ws.rs.customer.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import org.glassfish.bailiwick of jersey.client.ClientConfig; public form HelloClient { public static void main(Cord[] args) { String uri = "http://localhost:8080/HelloREST/residue/bonjour"; ClientConfig config = new ClientConfig(); Customer client = ClientBuilder.newClient(config); WebTarget target = client.target(uri); String response = target.request() .accept(MediaType.APPLICATION_JSON) .get(String.class); Organization.out.println(response); } }
This program merely sends a Get request to the server at the specified URI and reads the response. Run this program and you should see the post-obit output:
{"name":"greeting", "bulletin":"Bonjour tout le monde!"}
This is JSON response because the customer expects application/json as the accustomed media type.
Congratulations, you have washed your showtime hello world RESTful web services application, with both server and client. For your reference, yous can download the sample project in the attachments section below.
Y'all tin can also watch the video version of this tutorial beneath:
Other Java Web Services Tutorial:
- Java Grime RESTful Web Services Examples with Jersey and Tomcat
- Coffee Client Server XML Web Services (JAX-WS) Tutorial
- Java Web Services Tutorial using Apache Axis2, Ant and Tomcat
- How to code and deploy Java XML Web Services (JAX-WS) on Tomcat
- Monitoring Lather Messages using TCP/IP Monitor in Eclipse
- Using MTOM to optimize binary data transfer with JAX-WS web services
- Java Web Services Binary Data Transfer Example (base64 encoding)
About the Author:
Nam Ha Minh is certified Coffee programmer (SCJP and SCWCD). He started programming with Java in the time of Java i.4 and has been falling in love with Java since and so. Make friend with him on Facebook and lookout man his Java videos you YouTube.
Add together comment
How To Deploy Restful Web Service In Tomcat,
Source: https://www.codejava.net/java-ee/web-services/java-restful-web-services-tutorial-for-beginner-with-jersey-and-tomcat
Posted by: arellanothavent.blogspot.com
0 Response to "How To Deploy Restful Web Service In Tomcat"
Post a Comment