Software Training Institute in Chennai with 100% Placements – SLA Institute

Easy way to IT Job

Share on your Social Media

Java Servlets: Building Web Applications using Java

Published On: May 6, 2023

Java’s diverse, complex nature is one of its best advantages. It’s fine to create classic desktop and even mobile applications. But what if you want to start navigating the web and leave your present background behind? The good news is that the language comes with a full-featured Servlet API, allowing you to easily create reliable web applications. In this article, we are explaining Java Servlets for building web applications using Java. Accelerate your career by enrolling in our Java Training in Chennai at SLA Institute.

Introduction to Java Servlets

The Java applications known as Servlets run on Java-enabled web servers or application servers. They take care of the request that the web server sends, process it, create a response, and then transmit the response back to the web server.

Servlets are strong entities that, among other cool things, can grab data from the client through GET and POST requests, handle cookies and session parameters, process the data using additional application layers, and then return the result to the client in both text and binary formats (HTML, PDF, XML, GIF,   JPG, and so on), often by using a Java Server Pages (JSP) file. Understand the basics of Java and its OOPs concepts through our blog.

Working with Servlets

An essential stage in the process of developing and delivering applications over the Internet is working with Servlets. As previously mentioned, a servlet is a Java program that needs to be executed by a Java servlet engine on a Web server that supports Java. The Web browser receives the Servlet’s output. The NetBeans IDE 8.0.2 includes GlassFish Server Open Source 4.1, which offers built-in support for running Java Servlets. The server included with this book is used to run and showcase Servlets.

What is a Web Application?

A web application, often known as a web app, is a software program that can be accessed through a network like the Internet or an intranet by using a web browser. Despite the fact that many Web applications are now built in PHP or Perl natively, Java is still a popular programming language for creating Web applications. This is particularly true for enterprise Web applications, which are web-based business applications. For creating enterprise Web applications, Java EE offers a number of helpful components, including JSP, JSF, Servlets, client-side applets, Enterprise JavaBeans, JDBC, and various additional Web service technologies. The writing of Servlets as the available Web applications are the main topic of this article.

A web application development is essentially described as a hierarchy of directories and files within a common structure. There are two methods for accessing such a hierarchy:

  • The first is a separate directory and file for each item in the file system. This is referred to as the application in its unpacked state and is utilized for developing applications.
  • The second method involves packing all the subdirectories into a Web ARchive, or WAR file, which is zipped together. It is used for spreading the installed apps.

Web Server and Client

A web server is a piece of software that can handle client requests and reply to the client. For instance, one of the most popular web servers is Apache. A web server is a program that runs on a physical device and listens for client requests on a particular port. Software that facilitates communication with the server is known as a web client. Firefox, Google Chrome, Safari, and other popular web browsers are some of the most utilized browsers. The web client handles initiating a request, transmitting it to the server, interpreting the server answer, and presenting it to the user when we request something from the server (through URL).

HTML and HTTP

Since the web server and web client are two different types of software, a common language should be used for communication. HyperText Markup Language, or HTML, serves as the common language between the server and the client. A common communication protocol is required between the web server and client; HTTP (HyperText Transfer Protocol) serves as this protocol. The TCP/IP communication protocol is built on top of HTTP. Important components of an HTTP request include:

HTML Method: Action to be taken via HTTP Method; often GET, POST, PUT, etc.

URL: Access Page

Form Parameters: Form parameters, such as user and password information from the login page, are comparable to arguments in a Java function.

Simple HTTP Request

GET /FirstServletProject/jsps/hello.jsp HTTP/1.1

Host: localhost:8080

Cache-Control: no-cache

Important components of an HTTP response include:

Status Code: An integer status code identifies whether or not a request was successful. 404 for “Not Found” and 403 for “Access Denied” are a few of the well-known status codes.

Content Type: Content types include text, html, images, and PDFs. in addition to MIME type.

Content: Content is the real data that the client renders and displays to the user.

Sample HTTP Response

200 OK

Date: Wed, 07 Aug 2013 19:55:50 GMT

Server: Apache-Coyote/1.1

Content-Length: 309

Content-Type: text/html;charset=US-ASCII

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “https://www.w3.org/TR/html4/loose.dtd”>

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=US-ASCII”>

<title>Hello</title>

</head>

<body>

<h2>Hi There!</h2>

<br>

<h3>Date=Wed Aug 07 12:57:55 PDT 2013

</h3>

</body>

</html>

MIME Type or Content Type: The HTTP response header example shown above has the tag “Content-Type” in it. The server notifies the client of the MIME type, commonly known as the type of data it is sending, by sending it. It supports the client’s ability to render data for the user. The most popular mime types include text/html, text/xml, application/xml, and others.

Why are Servlets and JSPs necessary?

We need a different tool to create dynamic content because web servers are good for static HTML pages but are incapable of creating dynamic content or storing data in databases. For creating dynamic content, a variety of programming languages are available, including PHP, Python, Ruby on Rails, Java Servlets, and JSPs. Java Servlet and JSPs are server-side technologies that increase the functionality of web servers by supporting persistent data and dynamic response.

Building Web Application using Java Servlets

To create our first servlet application, we’ll use the “Eclipse IDE for Java EE Developers” tool. We will require a web container that supports Servlet technology since servlet is a server-side technology, so we will utilize the Apache Tomcat server. Setting it up is simple, and we’ll let you handle that portion. We can configure Tomcat with Eclipse to make development simpler; this facilitates application deployment and operation. The version of your Tomcat server should be listed under Server Runtime Environments; we use Tomcat 7.

Building Web Application using Java Servlets

Give the JRE information and the path of the Apache Tomcat directory so that the runtime environment can be added. Go to the Servers page and build a new server pointing to the runtime environment that was just added, as seen in the below image.

Java Servlets

Note: To make the Servers tab visible in the Eclipse window if it is not already, choose Window > Show View > Servers. To check sure the server is operating properly, try pausing and starting it. If you started the server from the terminal before starting it from Eclipse, you will need to stop it from the terminal and start it from Eclipse again for it to function properly. With our setup complete, we are now prepared to develop the first servlet and launch it on the Tomcat server. To create our servlet using Servlet 3.0 specifications, choose File > New > Dynamic Web Project and enter the runtime as the server we added in the previous step and module version as 3.0 as shown in the below image.

Java Servlets

You may either choose Finish to start the project right away or Next to see what other alternatives are available. To create our first servlet, go to File > New > Servlet and use the image below. Once more, we have the option to click Finish or use the Next button to explore further alternatives.

Java Servlets

It saves us time by creating our Servlet skeleton code when we click the Finish button rather than having to manually enter all the different methods and imports. In the doGet() method, which will be called in response to an HTTP GET request, we will now add some HTML code containing dynamic data. Below is a screenshot of our first servlet.

package com.journaldev.first;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Date;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebInitParam;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

 * Servlet implementation class FirstServlet

 */

@WebServlet(description = “My First Servlet”, urlPatterns = { “/FirstServlet” , “/FirstServlet.do”}, initParams = {@WebInitParam(name=”id”,value=”1″),@WebInitParam(name=”name”,value=”pankaj”)})

public class FirstServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public static final String HTML_START=”<html><body>”;

public static final String HTML_END=”</body></html>”;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public FirstServlet() {

        super();

        // TODO Auto-generated constructor stub

    }

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

PrintWriter out = response.getWriter();

Date date = new Date();

out.println(HTML_START + “<h2>Hi There!</h2><br/><h3>Date=”+date +”</h3>”+HTML_END);

}

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

// TODO Auto-generated method stub

}

}

Before Servlet 3, we had to provide information about the url pattern in the web application deployment descriptor, but Servlet 3.0 makes use of Java annotations, which are simple to comprehend and less likely to include errors. From the servlet editor window, select Run > Run on Server, and then select the options shown in the images below.

Java Servlets
Java Servlets

After hitting “finish,” Eclipse will open the browser and display the HTML page shown below.

Java Servlets

You can open it outside of Eclipse in any other browser and refresh it to see if the date is dynamic and constantly updating. If you look at the doGet() implementation, we actually create an HTML document as we write it in the response PrintWriter object, adding dynamic information where we need it.

This is how servlet is used to build HTML and deliver it in response. It’s a nice beginning, but if the answer is large and contains a lot of dynamic data, it is difficult to understand and manage and prone to errors. JSPs were first introduced for this main purpose. Similar to HTML but with extra features to add dynamic content where we need it, JSP is another server-side technology. JSPs are useful for presentations since they are simple to write because they are similar to HTML. This initial JSP program accomplishes the same task as the servlet mentioned earlier.

<%@page import=”java.util.Date”%>

<%@ page language=”java” contentType=”text/html; charset=US-ASCII”

    pageEncoding=”US-ASCII”%>

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “https://www.w3.org/TR/html4/loose.dtd”>

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=US-ASCII”>

<title>Hello</title>

</head>

<body>

<h2>Hi There!</h2>

<br>

<h3>Date=<%= new Date() %>

</h3>

</body>

</html>

If we execute the above JSP, we receive output similar to the image below.

Java
Java

Web Container

When a client submits a request to a web server, the web container, such as Tomcat, receives the request and forwards it to the appropriate resource (such as a servlet or JSP), which the web container uses to generate the response and sends it to the web server. The client then receives the response from the web server. You will learn about this comprehensively in our Advanced Java Training in Chennai.

If the request is for a servlet, the web container constructs HTTPServletRequest and HTTPServletResponse when it receives the request. The correct servlet is then located using the URL, and a thread is created for the request. Then it calls the servlet service() function, which then calls the doGet() or doPost() methods depending on the HTTP method. The dynamic page is created via servlet methods and added to the response. The container turns the response into an HTTP response and sends it back to the client after the servlet thread has finished. Web container performs crucial work including the following:

Communication Support – The container offers a simple method for servlets and JSPs to communicate with the web server. We don’t need to create a server socket to listen for requests from the website, parse those requests, and produce responses because of the container. The container handles all of these significant and challenging duties, leaving us free to concentrate on the business logic of our applications.

Lifecycle and Resource Management – The container manages the servlet life cycle. The servlets are loaded into memory by the container, which also initializes them, calls their methods, and destroys them. The container also offers tools like JNDI for managing and pooling resources.

Support for Multiple Threads – The container starts a new thread for each servlet request, which the thread terminates once it has been processed. Thus, saving time and memory, servlets are not initialized for each request.

JSP Support – JSPs do not resemble typical Java classes, and JSP is supported by web containers. Every JSP in the application is compiled, turned into a servlet, and then managed like other servlets by the container.

Miscellaneous Task – The web container controls the resource pool, does memory optimizations, runs the garbage collector, offers security configurations, supports numerous apps, performs hot deployment, and performs a number of other activities in the background that make our lives easier.

Web Application Directory Structure

The Web Archive (WAR) format is used to package Java Web Applications, and it has a predefined structure. To inspect the structure, you can export the dynamic web project mentioned above as a WAR file and unzip it. It will resemble the image below:

Java

Running the Web Application

If you’re anything like me, you’ll be eager to install the application on your own development platform so you can test it out for yourself and see whether it performs as well as I initially claimed. Simply take the following actions to do so:

  • Git (be sure to choose the version that is compatible with your operating system), Maven, and a servlet container—such as Apache Tomcat, Jetty, or JBoss Wildfly—are required. If your IDE comes pre-installed with one or more of these systems, you can utilize the embedded versions.
  • To import the application repository into your IDE, preferably as a Maven project, use Git to clone it to your local workstation.
  • Run the entire project when it has been deployed to the servlet container. Building a WAR file (Web archive) or an exploded WAR (also known as exploded deployment) and putting it in the servlet container’s default deployment folder constitutes deploying the project. Avoid wasting your time trying to carry out this step manually unless you absolutely have to because your IDE will frequently deploy the project for you automatically whenever you hit the Run button. For more information, consult the documentation for your IDE (in this case, IntelliJ IDEA). The default browser will launch once the project has been correctly deployed, and if everything goes as planned, you’ll see the client signup form.
  • There is plenty of potential for experimentation here, so try submitting the form with absolutely no values or even with a few missing values. The errors will be neatly displayed on top of the form in accordance with the problematic inputs. Finally, if you’re kind and submit the necessary information, you’ll see the welcome page.

Conclusion

You now possess all the knowledge and abilities necessary to begin creating your own Java web application without using any frameworks at all, which is the best part. All you have to do is utilize a rendering technology, like JSP or simple Java, and consume the Servlet API. Join SLA Institute for the Leading Java Training in Chennai with Best Practices.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.