Java REST web service with Gradle12 Dec 2017
In this blog post, we are just walking through fundamental steps of developing and running a REST web service by using Java Servlet and Gradle build tool.
What is REST?
Basically, REST stands for Representational State Transfer which is an architectural style based on HTTP protocol. REST concept is to separate the API structure into logical resources. HTTP methods (GET, POST, PUT, and DELETE) are used to operate with the resources.
About RESTful API design, you can learn more about the guidelines via following articles.
A servlet is a Web component that is managed by a container and generates dynamic content. Servlets are Java classes that are compiled to byte code that can be loaded dynamically into and run by a Java technology-enabled Web server or Servlet container.
Servlets run in a
servlet container which handles the networking side.
So, they are usually used to implement web applications which can respond to a particular type of network request, such as HTTP request.
So, we use it to build a web service which will run on an application server like Tomcat or Jetty.
Get our hands dirty
It is time to
show me your codes. All sample codes can be found at Github.
- Configuration file: It will reside under
- Java source codes: They are normally put under
WARplugin: It is used to build and generate
.warfile (WAR = Web application Archive) which includes JAR, JavaServer Pages, Java Servlets, XML, HTML, and other resource files. The
.warfile later will be deployed in web server.
apply plugin: "war"
- Gretty: A handy plugin to run web apps on embedded servlet container. It supports Tomcat and Jetty.
Java REST framework
Jersey simplifies REST web service development and abstracts low-level implementation details of the client-server communication.
- Test and build
- Run web app:
It is now successfully served under url
localhost:8080/api/notes. You can use a browser to check it out or you can test REST API using Postman which use can test both
In development, we use
Gretty plugin which automatically downloads web server and deploys web application for us. If we want to deploy in our production environment, we need to do it manually. Fortunately, it requires a few basic steps.
Gretty only supports
Jetty, you can choose a suitable sever for your need from this list of open-source web servers. The following steps of deployment process are general but I use
Jetty as examples.
- Download and install
.warfile inside project’s
- Paste it into
- Run server. Go inside
jettyand execute either following script.