Java Servlet

Coding

Introduction

When we go through the timelines of our social media websites or make our favourite purchase on the e-commerce website, or search for something in Google, we use the term ‘Server’ to refer to the remote entity which responds to all our ‘requests’. The requests are nothing but our requirement for information from our local computers.

Fig.1. Client and Server

The above figure illustrates the client and server. Both of them are computers in general, and they are connected via the internet. We can define a Client as a computer that can make a ‘request’ to a remote computer, and a Server as a computer that has the capability to understand the request and send a ‘response’ to the client. These request and response communications occur through a well-defined set of rules called ‘HTTP’ protocols.

The client computers make use of special software applications to communicate with servers and the most common applications are our well-known browsers like ‘Google Chrome’, ‘Mozilla Firefox’, Opera, Safari etc., When you type the address like http://www.facebook.com in the address bar of the browser and hit the ‘enter’ button, a request is sent from the client computer to the server. Here the request is to fetch the home page of the website.

The response from the server to the client is in a special markup language that can be understood by the browser, known as HTML – HyperText Markup Language. Basically, an HTML file consists of content and instructions to display the content. 

Static and Dynamic websites

The websites that we use on our everyday basis can broadly be classified into two types.

a. Static websites

b. Dynamic websites.

A Static Website has fixed content coded in HTML and stored on a web server. It always stays the same for every user who accesses the website. For example, https://en.wikipedia.org/wiki/Encyclopedia is a static website. While requesting the above website, every user in the world will get the same HTML content. The development of these websites is pretty simple and straightforward. 

However, think about https://www.facebook.com/. When you access your Facebook timeline, the Facebook server sends your computer a website coded in HTML. However, this HTML content is exclusively created for you. Based on your username and password, the Facebook server identifies you,. It creates your timeline based on your friends’ activities, your previous requests, updates from pages you follow and relevant advertisements exclusively created for you. These kinds of websites are called dynamic websites. 

Another example is your G mail inbox. The development of these dynamic websites involves more serious techniques when compared to static websites. The content available in the dynamic website changes according to the user’s location, time zone, time of the day, country, native language, etc. Mostly, these websites make use of modifiable databases on their back ends and deliver pages according to them. User’s activities or requests can make permanent changes on the database so that the user will get a customised view of the web page. For example, a user who accesses his email inbox can delete, forward, mark as essential or move the mail to another folder, resulting in changes in the database. These results modified HTML content for his inbox created at the server, sent to the client and displayed in his browser. 

Client-side and server-side technologies

As we have discussed, a set of technologies like HTML are used to render the websites on the client’s computer, which are called client-side technologies. HTML, CSS and Javascript are the fundamental client-side technologies. 

However, some technologies are running on the server-side to recognise a specific user and compose a dynamic website for that user. These technologies are called server-side technologies. Java servlets, JSP, Python, Ruby on Rails, PHP, are some of the popular server-side technologies.

Fig. 2. Static and Dynamic web pages

We can understand the difference with a simple analogy. Static websites are like ready-made cakes available in the Bakery shops. The customer can simply request a “black forest” cake, and it will be delivered without any customisation. The features, look and feel and taste, and all other cake characteristics will be exactly the same for every customer who orders it. On the other hand, Dynamic websites are like cakes ordered for special occasions with very specific requests for the colour, taste, name on top of the cake, ingredients etc. Here, the baker prepares the cake only after getting the specifications from the customer.

Dynamic web pages are created only when a user makes a request, and a separate set of technologies running on the server will take care of creating these pages and sending them to the users. 

In this article, we discuss the fundamentals of ‘Java servlets’, a specific server-side technology used to develop interactive web applications.

The role of protocols

Protocols are a predefined set of rules that instruct how a particular operation has to be done. For example, suppose you consider a traffic junction. In that case, there are vehicles travelling in all directions, and every one of them looks at the traffic light signal or the signal from the traffic police and behave accordingly. There are a set of rules and conventions which are obeyed by all the users, which results in a smooth operation. Even though the people speak different languages and use various types of vehicles, adhering to protocols make them collaborate and work together seamlessly. Similarly, if you consider computer networking, it is an area that involves disparate hardware and software technologies and products which are from various vendors across the globe. Ultimately, when client-server communication happens, all those differences are not visible to the user. Despite using different browsers, operating systems, computers, a user’s Facebook timelines will remain the same. He will get almost the same experience everywhere. He does not need to change the procedure to access the world wide web because of any disparities. It is possible only because of the protocols.

We have known that the Internet is a platform in which billions of devices worldwide are connected. How do they identify or locate each other to communicate? To solve this issue, we need an addressing mechanism or set of rules to be followed by every device connected to the internet. This set of rules is called ‘IP Protocol’. This protocol provides a specific format like 145.124.77.56 to address a device connected to the internet. While IP protocol enables addressing and locating the devices connected to the internet, the next level communication features are defined by another set of rules which is called ‘TCP protocol’. Thus, we make use of several protocols in various layers of computer internetworking.

The development of web applications comes under the application layer, and we have few specific protocols to take care of higher-level communication like client request and server response. The commonly used protocol in this layer is called ‘HTTP Protocol’. HTTP stands for HyperText Transfer Protocol. The name is simply because of the fact that this protocol defines the rules for transmitting HyperText (HTML coded) documents from server to client. All kinds of data like images, audio, video, text can be sent with the help of HTML.

Basics of Java Servlets

Servlet technology is used to create dynamic web pages on the server-side. It resides in the server and gets invoked based on the request from client programs. There are several technologies available to create and send dynamic web pages from the server. Collectively they are called server-side technologies, and Servlets have several advantages when compared to them. Since Servlets are based on Java language, they are very robust and scalable. 

Java Servlet ecosystem is supported by a rich API to develop powerful programs. API stands for Application Programming Interface, which is basically a collection of Java Interfaces, Classes and the necessary documentation to use them. Similar to a tool kit available for a specific task, API  provides all the necessary pre-built mechanisms to solve a programming problem. A detailed discussion on Java Servlet API is given below. 

With the help of Java servlet API, we can build server-side java servlet programs which will be executed as a part of the webserver to which the client sends the request. From the external viewpoint, the client sees that every request is responded to by the server. Internally, these responses are fabricated by the Java Servlet programs. Thus, Java Servlets play an important and powerful role in developing dynamic web pages. 

Servlet API

As mentioned in the previous section, API is how developers make use of the possibilities of a given technology, and Java Servlet API consists of several packages, classes and interfaces inside those packages and detailed documentation about them. Each class and interface have abstract and concrete methods which need to be understood to develop Servlet programs effectively.

The two most important packages are javax.servlet and javax.servlet.http packages. The classes and interfaces inside the javax.servlet package is not specific to any protocols, whereas the entities inside javax.servlet.http package is meant for http requests and responses.

The list of important Interfaces in javax.servlet package and a brief description can be found here. For a detailed view of the entire Java API, please visit the official documentation site https://docs.oracle.com/. 

Interfaces provide an abstraction of functionalities in the form of abstract methods. They clearly define the contract or the terms to be satisfied for a programming component. So the Java Servlet technology has provided us with few interfaces which need to implemented to meet the essential requirements. For example, ‘Servlet’ is an interface that needs to be implemented in the form of Generic Servlet or HTTPServlet. These classes declare the necessary methods for the servlet life cycle, and these methods can be overridden to implement the user’s requirements. So, an excellent understanding of Interfaces and Classes available in the Servlet API is essential to develop the applications. 

The list of important Interfaces in javax.servlet package

Servlet

ServletRequest

ServletResponse

RequestDispatcher

ServletConfig

ServletContext

The list of important Classes in javax.servlet package

GenericServlet

ServletInputStream

ServletOutputStream

ServletException

UnavailableException

The list of important Interfaces in javax.servlet.http package

HttpServletRequest

HttpServletResponse

HttpSession

HttpSessionListener

HttpSessionAttributeListener

HttpSessionBindingListener

HttpSessionActivationListener

The list of important Classes in javax.servlet.http package 

HttpServlet

Cookie

HttpServletRequestWrapper

HttpServletResponseWrapper

HttpSessionEvent

HttpSessionBindingEvent


Developing a Servlet Application

Based on all the concepts discussed above, let us try to build a basic servlet program.

To execute a Java Servlet program in your local computer, you should make your computer a Server so that it will receive the requests from the client browser, process them, and send a dynamic response. The simplest way to make your computer a server is by installing any lightweight web server software available on the internet. For our example, we use the Apache Tomcat web server, which can be downloaded from the Apache website.

Instructions to Install and Test Apache webserver:

  • Download the appropriate version of Apache tomcat from the following website: https://tomcat.apache.org/download-80.cgi., and store it in a local folder.
  • To run the web server on your computer, you have to set the following environment variables in your computer according to the local file path in which Apache Tomcat and Java software are stored in your computer.
  • The environment variables for your PC can set in the ‘Environment variables’ section of your ‘Advanced System Settings’, which can be obtained by right-clicking your ‘My Computer’ icon. Here is a sample screen for illustration.

Fig.3. Setting environment variables for tomcat server

[ PROVIDE CORRECT VALUES FOR FILE PATHS AS PER YOUR SYSTEM CONFIGURATION. THE GIVEN VALUES ARE JUST FOR REFERENCE]

Set the following environment variables with the values given.

  • $CATALINA_HOME : C:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.26
  • JAVA_HOME : C:\Program Files\Java\jdk1.6.0_14
  • classpath : C:\Program Files\Apache Software Foundation\Apache Tomcat 6.0.26\lib\servlet-api.jar
  • Go down to the folder ‘bin’ inside the Apache Tomcat root folder and run the file ‘startup.exe’. Now the server will be started, and you can see the server logs in a command prompt.
  • Now our server is running on the local computer. Basically, when we try to access any website, we provide the URL – uniform resource locator, which looks like http://wikipedia.org. In our example programs, we are going to use the server running in our local machine, so we will be using http://localhost:8080 to access the server.
  • Now, open the browser and hit the URL “http://localhost:8080”. 

This will provide the home page of Apache tomcat as shown here according to the version of the software that you have installed. If you are able to see a similar page in the browser, your service is running and ready to receive the requests.

IMG_256

Fig.4. Apache Tomcat Homepage

If you get the above screen, we are successful in running the server and accessing the server from our client – the internet browser. Now we can see how to develop a simple Java servlet program and execute that in this set-up.

A Servlet Example

Considering all the above concepts, let us develop a simple Java Servlet application to validate the username and password entered by the user. For example purpose, we are considering a login application. In this application, the user enters his username and password on the web page, and the Java Servlet program validates the credentials. For simplicity, we have avoided the database part of the application, and the validation happens in the servlet program itself. 

The purpose of the application can be understood with the help of the given figure.

Figure.5. Sample Java Servlet Application

The application consists of the following steps.

  • The server responds login.html file to the client, and the browser displays the login page, which has username and password text boxes and a login button.
  • The user enters the username and password in the text boxes and submits the ‘login’ button.
  • The entered username and password are sent to the server. The java servlet program LoginServlet.java is designated to handle this request. The servlet program checks that the value of the username is ‘admin’ and if the value of the password is ‘adminpass’. Ideally, the user names and passwords will be stored in a database, and the Java servlet program communicates with the database to validate the user credentials. However, to simplify our understanding here, we have skipped that part and assumed that the credentials entered by the user are validated in the java servlet program itself.

Execution procedure

To execute the Java servlet program, we need to understand the basics of the tomcat folder structure given below.

IMG_256

Fig.6. Apache Tomcat folder structure

To execute our sample application, we need to do the following.

  1. A new folder for each web application has to be created under the folder web apps. The name of the application must be the name of the folder. This is known as the context root of the application. 
  2. Compile the Java Servlet program and store the class file in the web apps/application_name/WEB-INF/classes folder.
  3. Store the static HTML pages in a dedicated folder inside the tomcat root folder.
  4. Inside the folder WEB-INF, we need to create an XML file named web.xml. The purpose of this file is to describe various features of the web application. In our example, we will see only the basic feature, in which a request from the client is mapped to the Java Servlet program in the server. The code is given below.

Web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <display-name>Servlet Hello World</display-name>    
    
 <servlet>
        <servlet-name>loginRequest</servlet-name>
        <servlet-class>LoginServlet</servlet-class>
 </servlet>
 <servlet-mapping>
        <servlet-name>loginRequest</servlet-name>
        <url-pattern>login</url-pattern>
 </servlet-mapping>
</web-app> 

Login.html

<html>
	<head>
		<title>Login Page</title>
	</head>
	<body>
		<form name="loginForm" method="post" action="login">
			<table width="20%" align="center">
				<tr>
				<td colspan=2><center><font size=4><b>User Login</b></font></center></td>
				</tr>
				<tr>
				<td>Username:</td>
				<td><input type="text" size=25 name="userid"></td>
				</tr>
				<tr>
				<td>Password:</td>
				<td><input type="Password" size=25 name="pwd"></td>
				</tr>
				<tr>
				<td ><input type="submit" value="Login"></td>
				</tr>
			</table>
		</form>
	</body>
</html>

LoginServlet.java

import java.io.IOException;  
import java.io.PrintWriter;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
public class LoginServlet extends HttpServlet {  
public void doPost(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException {  
  
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
          
    String name=request.getParameter("userid"); 
	Stirng password = request.getParameter("pwd");
	if(name.equals("admin") && password.equals("adminpass"))
		out.println("<html><body style="background-color:powderblue;">");
		out.println("Your login is successful");
		out.println("</body></html>");
		out.close();
	else
		out.println("<html><body style="background-color:powderblue;">");
		out.println("Your login credentials are wrong");
		out.println("</body></html>");
		out.close();
	
    }  
  
}  

The LoginServlet.java – explained.

The first part of the program is importing necessary packages and classes to run the servlet program. The LoginServlet.java is extending from the base class HttpServlet, so we need to import javax.servlet.http.HttpServlet. 

javax.servlet.http.HttpServlet;  

javax.servlet.http.HttpServletRequest;  

javax.servlet.http.HttpServletResponse; 

HttpServlet is an abstract class that needs to be subclassed to develop an HTTP servlet for any custom purpose. Once we do that, it is mandatory that any one of the following methods need to implemented.

doGet – for HTTP GET requests from the clients

doPoST – for HTTP POST requests

While the above two are the most common methods overridden, there are other two methods, namely doPut and doDelete for HTTP PUT and HTTP DELETE requests. So, the need for invocation of these methods is coming from the client request. 

Also, init() and destroy() methods are commonly overridden to manage the resources. These methods have been explained in the ‘Servlet Life Cycle’ section of this article.

In the case of HTTPServlet implementation, there is no need to override the service method since it dispatches the request to appropriate handler methods like doGet or doPost.

HttpServletRequest and HttpServletResponse are the two important interfaces required for any servlet operation. They represent the request and response information, and they are created by the servlet container and passed as arguments to the handler methods.

In the given example, we have overridden doPost method with request and response arguments. The request object would contain all the data sent from the client-side. In our case, the user has invoked this servlet from a login form after providing the user name and password. Thus, these two values will be available in the request object. During the entry of the doPost method, response object will be empty, and it will be populated in due course.

In the next part of the program, the response object is being built step by step. The content type is set as text or HTML. We use a PrintWriter object from the java.io package to write data in the response object. Here, we manually check if the username and password values are ‘admin’ and ‘adminpass’ manually, without hitting any database for simplicity. In the case of proper credentials, the response object is populated with HTML code for a success message. On the other hand, if the credentials are not correct, then HTML code for an error message is written in the response object. At the end of the method, the response object will be sent to the client as HttpResponse. These manipulations are taken care of by the Servlet container, and the developer has no role in this. Though the server-side java program and the client-side browser are two entirely different technical entities, both follow the HTTP protocol to achieve communication among them.

In a more severe servlet program, the request would be redirected to dedicated java programs and several databases intensive operations. 

Description of Flow of events

  1. The user enters the URL http://localhost:8080/sample/login.html in the browser.
  2. The HTML file is located in the tomcat root folder for simplicity, and the server will send the HTML code to the client, and the browser displays the login website.
  3. The user enters the username and password in the given text boxes of the website and clicks the login button.
  4. In th,e HTML file, user-entered data are captured in an HTML element called ‘form’, which has been written as follows. 

<form name=”loginForm” method=”post” action=”login”>

  1. The meaning of the above statement is that when the form is submitted by clicking the submit button, the data entered inside the form (in all the HTML input controls like text boxes, checkboxes, radio buttons etc.,) will be sent to the server-side with the token ‘login’. This token will be used to resolve which servlet program in the server has been designated to process this request.
  2. In the web.xml file, the mapping between the token ‘login’ and the Java servlet program ‘LoginServlet.java’ has been configured, as you can see in the above code.
  3. So, whenever the form is submitted with a username and password, the LoginServlet.java program will be invoked. If the entered values are correct, the user will get a success page, or the user will be displayed an error page, as illustrated in the figure.

Servlet Life Cycle

A servlet life cycle is an entire process starting from the user’s request, servicing the request and removal of servlet instance from the server. It is managed primarily by three different methods, from its creation to destruction. These methods are called the servlet container. 

As illustrated in the figure, the servlet life cycle can be explained in the following steps.

Figure 7. Servlet life cycle

Step 1: In the initial state, the servlet java program will be available in the server in the inactive condition. The instance of the Servlet would not have been created. The life of the servlet starts when the user makes a request to the servlet. (As in the above example, a username and password are sent to the servlet for validation )

Step 2: When the user request reaches the server, and the server recognises a particular servlet program needs to be instantiated to service this request, the java servlet object will be created, and the initialisation process takes place. This is done by the method init(). Once the init() method is called, the servlet object is now ready to service the requests. In the init() method all the necessary preparation activities are done to service the requests. For instance, establishing a connection to the database server can be done in the initialisation state, and it will be maintained for the entire life cycle of the servlet. The init() method is called only once in the life cycle of the servlet. Thus, only one servlet object is created in the entire life cycle of a servlet. 

The structure of the init() method is given below.

public void init() throws ServletException {

   // Initialization activities…

}

Step 3: Once the servlet object is created and initialisation is completed, the object is ready to service the user’s requests. The service() method take care of servicing the user’s request with appropriate action, which can be a database related operation or some programming logic or anything similar to that. For every consecutive request from a client, only the service() method will be called again and again. The request processing and response creation are actually happening only in this method. This method can make use of another set of methods including doGet() and doPost(),  to service the request further. These methods can be overridden by the programmer to perform the actual task and to create the dynamic response. 

Here we need to understand that only one of object servlet is available, and multiple requests are serviced by the object with the help of a concept called Multithreading which is a significant characteristic of java programming. 

The structure of the service() method is given below.

public void service(ServletRequest request, ServletResponse response) 
   throws ServletException, IOException {
}

The structure of doGet()
public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
   // Servlet code written to perform the actual task
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
   // Servlet code written to perform the actual task
}

Step 4: At the end of the application, when there are no more requests, the servlet object will be removed from the memory or destroyed. Basically, this is called as garbage collection, an automatic process takes place in Java Virtual Machine to clear the memory of unused objects. It is performed by destroy() method. During this method, all the closing formalities of a servlet program are done. It can be clearing any buffers used for data storage/transmission or closing any database connections, releasing resources etc. Like the init() method, destroy() method is called only once in the lifetime of the servlet.

The destroy method structure is given below.

public void destroy() {
   // The code for finalization procedure...
}

Conclusion

Java Servlet technology is an important part of J2EE – Java Enterprise Edition, which is the most robust solution available for developing server-side solutions. This article tries to touch upon few introductory topics in the Java servlet. J2EE provides a rich set of technologies like JSP, JSF, EJB etc., which are used in developing large enterprise web applications. The web application space has been occupied with several new technologies like node.js, and the readers are advised to obtain a proper understanding of their specific requirements and to choose the technology. Also, learn java programming for free and get a course completion certificate.

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top