Servlets in Java

Learn How to Create Web Applications using servlets in Java

Before starting with servlets in java, it is important to remember the basic understanding of web browsers and servers. Servlets In Java are web pages generated by the web servers in response to the request sent by the clients. It is essential to know-how server and client work in cooperation to provide the valid contents to the user.

Servlets provide many advantages as compared to other parallel technologies. As an example let us consider a request for a static web. In the browser window, the user enters UNIFORM RESOURCE LOCATOR (URL). After that browser generates an HTTP request to the appropriate web browser. Then the webserver maps this request to a particular file.

thus, That file is then returned in an HTTP response to the browser. The HTTP header indicates the type of content. The Multipurpose Internet Mail Extension(MIME) is beneficial for this justification. E.g. Ordinary ASCII text has got MIME-type text. The Hypertext Markup Language(HTML) source code of a webpage has got MIME-type of text/html.

therefore, This was about the static page, now let us consider dynamic content. although An example could be an online bookstore. thus, It uses a database to store information related to its business, including book details like price, availability, order, etc.

CGI

The communication with the Webserver through an interface also refer as Common Gateway Interface (CGI). It thus allows the separate process to read data from the HTTP request and write data to the HTTP response. For the development of the CGI program, a variety of different languages were used. E.g. C, C++, and Perl.CGI suffered because of serious performance problems.

however, The reason is establishing a separate process for each client request was expensive in terms of processor and memory resources. though It is difficult to open and close the database connection for each client request. One more drawback of the CGI program was that they were not platform-independent. Because of this, other techniques were introduced.

Servlets can be defined as a java class that extends the functionality of a web server by dynamically generating web pages.

As we know Java has an enormous collection of Java class libraries. 

Types of Servlets In Java:

 Servlets are generally of two types : 

  1. Generic Servlets
  2. HTTP Servlets 
  1. Generic Servlets: 

Generic servlets extend javax.servlet.GenericServlet package. therefore, They are protocol independent. thus, they do not contain inherent HTTP support or any other of the transport protocol.

  1. HTTP Servlets :

HTTP servlet extends javax.servlet.HttpServlet. so, This type of servlet is having built-in HTTP protocol support. These servlets are more suitable in a Sun Java System Web Server environment.

Use of Generic Servlet:

  • The GenericServlet class is also used to implement the basic life cycle method for a servlet.
  • thus, The GenericServlet class is used to enforce the Servlet and ServletConfig interfaces.

Servlet Life Cycle:

  • The Life Cycle of the servlet is easy to understand. however, There are three methods central to the life cycle of a servlet. The methods are as follows: 
  1. init( )
  2. service( )
  3. destroy( )

These methods are carried out by every servlet and are executed at particular times by the server.

To consider these methods, let’s consider the example. Let’s first assume that a user enters a Uniform Resource Locator into the web browser. Then the web browser produces an HTTP request for this URL and sends it to the relevant server.

Secondly, this HTTP request is received by the webserver. The server maps this request to a specific servlet. Then the servlet is dynamically obtained and loaded into the server’s address space.

1. Init()

In the third step, the server invokes the init( ) method of the server. When the servlet is first loaded into memory, this method is invoked. The initialization parameters configure itself so that it can be passed to the servlet.

2. Service()

Fourthly, the service( ) method invoked by the server. so, The service method is called to process the HTTP request. The servlet can read data that has been provided in the HTTP request, and also it can formulate an HTTP response for the client.

although, The servlet is available to process any other HTTP request sent by clients and it remains in the server’s address space. The service( ) method is called for every HTTP request.

Lastly, the server may decide to unload the servlet from its memory. The server needs the algorithm by which this decision is taken and those are specific to each server.

3. Destroy()

The server gives a call to the destroy( ) method to relinquish resources like file handlers that are allocated for the servlet. The important data is saved to a persistent store. so, The memory allocated for the servlet and its objects can be thrown into the garbage collection.

To know servlets in a better way we need to understand how it is designed and tested. Following are the important steps which desire to be followed.

  1. Create and compile the servlets source code.
  2. Start the servlet runner utility.
  3. Start a web browser and request the servlet.
Let’s see the example. To start, create a file named WelcomeServlet.java that contains the following program:
  1. Create and compile the servlet source code.
  2. Start the servlet runner Utility.
  3. Start a web browser and request the servlet.

Simple servlet program for Arithmetic Operations:

so, Write a servlet program which will take two number from the user and display the addition, subtraction, multiplication and division of that two number.

Classes of Servlet:

  1. GenericServlet: This class is also used for implementing the Servlet and ServletConfig interface.
  2. ServletInputStream: Provides an input stream for reading requests from a client.
  3. ServletOutputStream: This class thus supports an output stream for writing a response to a client.
  4. ServletException: This shows a servlet error occurred.
  5. UnavailableException: also Displays that servlet is not available.

The javax.servlet.http Package:

The javax.servlet.http package is made up of a number of interfaces and classes that are commonly used. so, Its functionality makes it easy to build servlets that work with an HTTP request and responses.

Core Interfaces of java.servlet.http package::

  1. HttpServletRequest: This interface enables servlets to read data from an HTTP request.
  2. HttpServletResponse: The interface also enables servlets to write data to an HTTP response.
  3. HttpSession: The HttpSession interface allows session data to be read and written.
  4. HttpSessionBindingListener: This interface thus informs an object that it is bound to or unbound from a session.

Classes of javax.servlet.http package :

  1. Cookie: Cookie class allows state information to be store on the client machine.
  2. HttpServlet: Provides methods to handle HTTP requests and responses.
  3. HttpSessionBindingEvent: Used to indicate when a listener is bound to or unbound from a session value or that a session attribute changes.

Handling HTTP Request and Responses:

  • The HttpServlet class supports some exclusive method which handles the different types of the HTTP requests. so, These methods are doDelete( ), doGet( ), doPost( ), doPut( ) and doTrace( ).
  • Handling HTTP GET Request( doGet( ) method) 

let’s see the below code. The file name is CellphoneGet.html.

  • CellphoneGetServlet.java:

Steps for running the above program: 

  1. Start Tomcat server, if it is not already running.
  2. Display the Web page in a browser.
  3. Select a cellphone.
  4. Submit the Web page.
  • Parameter for an HTTP GET request is included as part of the URL that is sent to the webserver. so, If the user chooses the Nokia option and submits the form. The Uniform Resource Locator sent from the browser to the server is

(http://localhost:8080/example/servlet/CellphoneGetServlet?Cellphone=Nokia )

LoginServlet.java:

Contents of web.xml file: 

Handling HTTP POST requests : ( doPost( )method)  To understand this we will consider a program : Cellphone.html

CellphonePostServlet.java : 

Servlet Redirection :

  • Using the status code header, servlets can redirect the requests. This can be achieve by sending instructions to the client for using another URL in the response.
  • Redirection is mainly use when a document moves or for load balancing or maybe for simple randomization.
  • The below example is also a demonstration of a servlet for random redirection. It’ll send the client to a random website from the website listed in its program. A website will randomly by the servlet and the user will be redirects to the page.
  • In the code above, redirection happens because of the following two lines.

response.setStatus(response.SC_MOVED_TEMPORARILY);

response.setHeader(“Location”, site);

BASIC CONCEPTS OF SESSIONS, COOKIES AND SESSION TRACKING :

  • A cookie is the piece of information that stores the session-related data like username, password, time, data, etc.
  • Cookie class is part of javax.servlet.http package. It is use for handling cookies.
  • This class creates a cookie that is a small amount of information that is send by a servlet to a web browser. It is save by the browser and then again send back to the server.
  • A value present in the cookie can be uniquely identifies and it represents a client. That is why cookies are mainly in use for session management.
  • Different methods used by the cookie class are as follows:

getName( )

getPath( )

getValue( )

setValue( )

Files of cookies : 
  1. AddCookie.html: This program permits a user to specify a value for the cookie named MyCookie.
  2. AddCookieServlet.java:  This program processes the submission of AddCookie.html.
  3. GetCookiesServlet.java: Program used to display cookie values.
AddCookie.html
AddCookieServlet.java
GetCookieServlet.java

Steps to running the above program:

  1. Start Tomcat.
  2. Run AddCookie.html in the browser.
  3. Enter a value for MyCookie 
  4. Request the following URL via the browser.

http://localhost:8080/examples/servlet/GetCookieServlet

  1. The output will be the name and value of the cookies shown in the browser.

Session and session tracking:

  • As we know that HTTP is a stateless protocol, each request is an individual request. But in some applications; it is require to save state information. Because of that information can be collected from several interactions between a browser and a server. This mechanism is suppose by sessions.
  • The session is the time since the user logged into the system till the logout time. The session may be even the time between user visits the page and close it.
  • A session is created using following methods:

getSession( )- This method is from HttpServletRequest class.It returns HttpSession object.

This object stores a set of bindings that associate names with objects.

  • Maintaining and storing the information related to the session is call as session tracking. The different information about the session like time, date, user session ID, etc can be stored.

Conclusion Servlets In Java:

Servlets are the basic java objects utilize in handling incoming HTTP requests. Although building Servlets by enforcing the default HttpServlet java interface is the long way to go about installing scalable Java web applications.

thus, appreciating the fundamentals of how they work is very crucial as it is use by more progressive frameworks like Spring which has become a major tool in building scalable Java web applications.

written by: Vickky Bopche

reviewed by: Soutik Maity

If you are Interested In Machine Learning You Can Check Machine Learning Internship Program
Also Check Other Technical And Non Technical Internship Programs

Leave a Comment

Your email address will not be published. Required fields are marked *