Java Servlet Tutorial

Welcome to the Java Servlet Tutorial, which is part of the Java Certification course offered by Simplilearn. We will learn about Java Servlet and various other elements of Java Servlet in this tutorial.

Objectives

On completion of this Java Servlet tutorial, we will be able to:

  • Discuss Java Servlet Architecture
  • Explain the important terms related to Java Servlets
  • Understand Servlet Life Cycle
  • Explain ServletRequest, ServletResponse, ServletConfig, and, ServletContext
  • List the steps to configure and deploy Servlet
  • Explain Servlet Collaboration

Introduction to Java Servlet

Let us look at the topics covered below under this section.

  • Static and Dynamic Response
  • Client-Server Architecture with Java Servlet
  • The Web Container
  • Client-Server Architecture with the Web Container

Why Servlet?

We have learned that web server generates two types of responses:

  • Static
  • Dynamic

However, a web server can generate static responses in the form of HTML. To generate a dynamic response, a programming language that performs dynamic operations is needed.

What is a Servlet?

Servlet is a Java program that can perform dynamic operations and send it to the web server. The web server then sends this response to the web client.

Let’s look at these two types below:

Static Response

Every time we type HTTPS://www.google.com/ in your browser, you are directed to the Google homepage. This is called a static page as the web server displays the same HTML page every time the client requests.

Dynamic Response

When users log in to their Facebook account, different pages will be generated for different users. These are not Static Pages that are saved on the server-side and later displayed. Instead, they are dynamically generated based on the user ID. So you would see the pages relevant to your login. This requires multiple responses from the server, called Dynamic Response and hence we need Servlets, which is programming capability on the server side to generate such dynamic content.

Client-Server Architecture with Java Servlet

Let us understand Client-Server Architecture below.

https://www.simplilearn.com/ice9/free_resources_article_thumb/client-server-architecture.JPG

  • We have a user connected via browser
  • Sending HTTP requests to the web server
  • The server has the web container containing servlet, which gathers data from the database and generated output as HTML.
  • The HTML file is sent to via HTTP Response to the client browser.

Web server is a program that sends HTTP response, and Servlet is a Java Program that deals with classes and objects. How is the response generated in the HTTP format?

It is done by the web server at work that purely works on HTTP protocol. This is done using a web container present on the web server.

Let’s understand the web container below.

Web Container

A web container is built on top of the Java EE platform, and it implements the Servlet API and the services required to process HTTP (and other Transmission Control/Internet Protocol [TCP/IP]) requests.

  • Java Servlets are components that must exist in a web container. Web container activates the Servlet that matches the requested URL by calling the service method on an instance of Servlet class.
  • Activation of the service method for a given HTTP request is handled in a separate thread within the web container protocol.

Client-Server Architecture with Web Container

The lifecycle of a Servlet is controlled by the web container in which the Servlet has been deployed.

https://www.simplilearn.com/ice9/free_resources_article_thumb/client-server-architecture-web-container.JPG

  • The Client browser sends an HTTP Request to the web server
  • Web server forwards requests to Web Container
  • Web Container forwards it to the Servlet in form of the request object
  • Servlet generates response object and sends it to the Web Container
  • Web container converts it into equivalent HTTP response to the web server
  • The web server sends HTML content via HTTP response back to the client browser.

Servlet API, Interface, and Methods

Given below are some of the topics discussed in this section.

  • Servlets API
  • Servlet Interface and Classes
  • Servlet API Interface
  • Servlets API Hierarchy to Create Servlet
  • Servlets Methods
  • GenericServlet Abstract Class
  • GenericServlet Abstract Class Methods
  • HTTPServlet Abstract Class Methods

Learn more about Java Certification course details. Click to know more!

Servlets API

Servlet API contains a number of classes and interfaces that describe the contracts between a servlet class and the runtime environment provided for an instance by a conforming servlet container. Servlet API provides the following two packages that contain its classes and interfaces:

javax.servlet.*;

Classes and interfaces define the contracts between a Servlet class and the runtime environment provided for an instance of such a class by a conforming Servlet container.

javax.servlet.HTTP.*;

Classes and interfaces define the contracts between a Servlet class running under the HTTP protocol and the runtime environment provided for an instance of such a class by a conforming Servlet container.

Servlet Interface and Classes

This largely is the ecosystem in terms of the set of functions, API’s, Interfaces and classes available as part of Java Servlet API.

https://www.simplilearn.com/ice9/free_resources_article_thumb/servlet-interface-class.JPG

Servlet API Interface

The table below lists out some of the interface functions.

javax.servlet.FilterConfig

Passes information to a filter during initialization

javax.servlet.RequestDispatcher

Sends request and response object to any resource (such as a Servlet, HTML file, or JSP file) on the server

javax.servlet.Servlet

Defines methods that all Servlets must implement

javax.servlet.ServletConfig

A Servlet configuration object used by a Servlet container to pass information to a Servlet during initialization

javax.servlet.ServletContext

Defines a set of methods that a Servlet uses to communicate with its Servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file

javax.servlet.ServletContextAttributeListener

Implementation of this interface receives notifications of changes to the attribute list on the Servlet context of a web application

javax.servlet.ServletContextListener

Implementation of this interface receives notifications about changes to the Servlet context of the web application they are a part of

javax.servlet.ServletRequest

Defines an object to provide client request information to a Servlet

javax.servlet.ServletRequestAttributeListener

A ServletRequestAttributeListener can be implemented by the developer interested in being notified of request attribute changes

javax.servlet.ServletRequestListener

A ServletRequestListener can be implemented by the developer interested in being notified of requests coming in and out of scope in a web component

javax.servlet.ServletResponse

Defines an object to assist a Servlet in sending a response to the client

Servlets API Hierarchy to Create Servlet

Given below is the hierarchy that needs to be followed to create a Servlet.

javax.servlet.Servlet (I)

All Servlets must implement the Servlet interface that defines lifecycle methods

javax.servlet.GenericServlet(C)

Servlet can also be created by extending GenericServlet abstract class. GenericServlet abstract class implements all methods of Servlet interface except service method.

javax.servlet.HTTP.HTTPServlet(C)

Another way of creating a Servlet is to extend HTTPServlet abstract class. HTTPServlet abstract class extends GenericServlet abstract class

User Defined Servlet

I —Interface, C—Class.

Servlet Methods

Servlet interface has 5 methods:

  1. init
  2. service
  3. destroy
  4. getServletInfo
  5. getServletConfig

Let us look into the 5 methods.

init

The init method is called by Servlet container to indicate to a Servlet that it is being placed into service. It is declared as:

void init (ServletConfig config)

service

The service method is called by the Servlet container to allow the Servlet to respond to a request. So it takes a response and request object. It is declared as:

public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException

destroy

The destroy() indicates that the Servlet is being taken out of service and needs to be destroyed. It is declared as:

public void destroy()

getServletInfo

The getServletInfo method returns information about the Servlet. It is declared as:

public java.lang.String getServletInfo()

getServiceConfig

Returns a ServletConfig object that contains initialization and start-up parameters for the Servlet. It is declared as:

public ServletConfig getServletConfig()

GenericServlet Abstract Class

  • GenericServlet implements Servlet interface.
  • It defines Servlet generic and is independent of protocols.
  • It doesn't give implementation for the service method of Servlet interface.
  • If your Servlet extends Generic Class, implementing service method is necessary.

GenericServlet Abstract Class Methods

Some of the Abstract Class methods mentioned below are:

void init(ServletConfig config)

Called by the Servlet container to indicate to a Servlet that the Servlet is being placed into service

void log(java.lang.String msg)

Writes the specified message to a Servlet log file, prepended by the Servlet's name

void log(java.lang.String message, java.lang.Throwable t)

Writes an explanatory message and a stack trace for a given Throwable exception to the Servlet log file, prepended by the Servlet's name

abstract void service(ServletRequest req, ServletResponse res)

Allows the Servlet to respond to a request.

public abstract class GenericServlet

Extends java.lang.Object implements Servlet, ServletConfig, and java.io.Serializable

java.lang.String getInitParameter(java.lang.String name)

Returns a String containing the value of the named initialization parameter, or returns null if the parameter does not exist

java.util.Enumeration getInitParameterNames()

Returns the names of the Servlet's initialization parameters as an Enumeration of String objects, or returns an empty Enumeration if the Servlet has no initialization parameters

ServletContext getServletContext()

Returns a reference to the ServletContext in which the Servlet is running

java.lang.String getServletName()

Returns the name of this Servlet instance

void init()

A convenient method which can be overridden so that there's no need to call super.init(config)

HTTPServlet Abstract Class Methods

It provides an abstract class to be subclassed to create an HTTP Servlet suitable for a website.

Following is the list of methods mentioned in the table:

public abstract class HTTPServlet

Extends GenericServlet Implements java.io.Serializable

doGet

Used if the Servlet supports HTTP GET requests

doPost

Used for execution of HTTP POST requests

doPut

Used for HTTP PUT requests

doDelete

Used for HTTP DELETE requests

init and destroy

Used to manage resources that are held for the life of the Servlet

getServletInfo

Used by the Servlet to provide information about itself

Servlet Life Cycle

The lifecycle of a Servlet is controlled by the container in which the Servlet has been deployed. When a request is mapped to the Servlet, the container performs the following steps if an instance of the Servlet does not exist.

  • It loads the servlet class.
  • It creates an instance of the servlet class.
  • It calls the init method.
  • Calls the service method.
  • Calls the destroy method.

Configure and Deploy Servlet

Let’s look at the topics mentioned below under this section.

  1. Create dynamic web project in eclipse
  2. Add Server to the project
  3. Run server (Apache Tomcat)
  4. Create HTML file
  5. Click on src and create Servlet
  6. Create a web.XML configuration file
  7. Configuring a Servlet Definition
  8. Configure the Servlet Mapping
  9. Activating the Servlet in Web

Steps To Create a Dynamic Web Project In Eclipse

Create a dynamic web project in eclipse.

https://www.simplilearn.com/ice9/free_resources_article_thumb/create-project-eclipse.JPG

We will add a web XML by selecting but the web XML checkbox and Click finish

https://www.simplilearn.com/ice9/free_resources_article_thumb/new-dynamic-project.JPG

Steps To Add Server To Project

Given below are the steps involved to add the server to project.

  1. Click on “Windows” in the menu bar.
  2. Click on “preference”.
  3. Click on “Server”.
  4. Click on “Runtime Environment”.

Run Server (Apache Tomcat)

The steps to run Apache Tomcat server are:

  1. Run Apache with eclipse
  2. Click on “Window.”
  3. Click on “show view.”
  4. Click on ”server.“
  5. Click on ”new server.“
  6. Click on ”next.“
  7. Click on “next,” the server is now added to your project.
  8. To start the server, right click on “Tomcat Server.”
  9. Click on “Restart option.”

Create HTML File in web content folder

The image below gives the code structure for creating HTML file.

https://www.simplilearn.com/ice9/free_resources_article_thumb/create-html-file.JPG

Create Java Class (Servlet)

The image below gives the code structure for creating java class Servlet.

https://www.simplilearn.com/ice9/free_resources_article_thumb/create-java-servlet.JPG

Create a web.XML File

Steps required to create the web.XML file are mentioned below:

  • The web.XML deployment descriptor is used by the web container to configure servlet component. The Servlet definition also specifies the fully qualified class that implements the component.
  • The web container creates an instance of each Servlet definition in the deployment descriptor
  • There can be multiple Servlet definitions.

Configure A Servlet Definition

Inside the web container of the web server, inside the deployment destructor file, we will prove the configuration name and the package name for the servlet. The web container will create only one servlet object in the deployment descriptor.

https://www.simplilearn.com/ice9/free_resources_article_thumb/configure-servlet-definition.JPG

Configure A Servlet Mapping

Steps to configure Servlet mapping:

  • The deployment descriptor is also used to configure a URL pattern that is used to invoke the Servlet component.
  • The web container receives an HTTP request for specific URLs, and it matches the URL to either a physical component or a logical mapping to a Servlet component.

https://www.simplilearn.com/ice9/free_resources_article_thumb/configure-servlet-mapping.JPG

After Configuring, when we hit a URL of localhost port no: 8080(default port for TOMCAT), and the name of the file we are looking for, it will do a lookup in the web container, and it will check the deployment descriptor whether there is a mapping to the correct servlet. It will then process it, generate an HTML file and sends it back to client-server.

When the URL pattern becomes HTTP://localhost:8080/project name/check, the Web container looks in web.XML to find the location of the servlet class using servlet name and servlet mapping.

https://www.simplilearn.com/ice9/free_resources_article_thumb/configure-servlet-mapping-url.JPG

Activating The Servlet In Web

When the user selects the home page by the way of URL HTTP://localhost:8080/project name/urlpatterns, the web container responds with the HTML code for the home page.

Servlet Request and Response

In this section, we will be covering:

  • ServletRequest
  • ServletRequest Interface
  • Servlet Response

ServletRequest

The points below helps us understand ServletRequest.

  • It defines an object to provide client requests information to a Servlet
  • The Servlet container creates a ServletRequest object.
  • Servlet container calls service method by passing ServletRequest object.
  • This object provides data including parameter name and values, attributes, and an input stream.

ServletRequest Interface - Methods

Some of the methods available are given below:

getAttribute():

returns the value of the the name

getAttributeNames():

returns enumeration containing the names of the attributes.

getCharacterEncoding():

returns the name of the character encoding used in the body of the request

getContentLength():

returns the length of the request body (in bytes)

getContentType():

returns MIME type of the body of the request

getInputStream():

retrieves the body of the request as binary data

getLocale():

returns the preferred locale, that the client will accept

getLocales():

returns an enumeration of local objects

getLocalName():

returns the host name of the IP interface on which the request was received.

getLocalPort():

gives you the port number

getParameter(): returns

a perimeter value based on the key

getParameterMap():

returns java.util.Map

getParameterNames():

returns an Enumeration

getParameterValues()

returns an array of string objects containing all of the values that given request parameter has

getProtocol()

gives us the protocol

getReader()

retrieves the body of the request as character data using BufferedReader

setAttribute()

stores an attribute in the request

Servlet Response

  • It gives us a set of methods and properties that allow us to access the response via the response object.
  • It defines an object to assist a Servlet in sending a response to the client.
  • The Servlet container creates these objects to call Servlet’s service method.
  • To send the binary data in a MIME body response, used the ServletOutputStream returned by getOutputStream().
  • To send character data, use the PrintWriter object returned by the function called response.getWriter(). To mix binary and text data, for example, to create a multipart response, use a Service OutputStream and manage the character sections manually.

ServletConfig and ServletContext

Let us discuss ServletConfig and ServletContext below in details.

ServletConfig

Let us understand ServletConfig below:

  1. The config object is created by the web container based on the initialization parameters specified in the deployment descriptor file or web.XML file
  2. There has to be one ServletConfig per Servlet.

ServletContext

Let us understand ServletContext below:

  1. To share application specific data crossed independent web components
  2. One ServletContext per application
  3. The context object is accessible to all the Servlets in the web application.
  4. A ServletContext object is the runtime representation of the web application.

ServletConfig Methods

Let us look at some of the methods mentioned below in the table.

java.lang.String getInitParameter(java.lang.String name)

Returns a String containing the value of the named initialization parameter, or returns null if the parameter does not exist

java.util.Enumeration getInitParameterNames()

Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or returns an empty Enumeration if the servlet has no initialization parameters

ServletContext getServletContext()

Returns a reference to the ServletContext in which the caller is executing.

java.lang.String getServletName()

Returns the name of this servlet instance

public interface ServletContext

Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file

java.lang.Object getAttribute(java.lang.String name)

Returns the servlet container attribute with the given name, or returns null if there is no attribute by that name

java.util.Enumeration getAttributeNames()

Returns an Enumeration containing the attribute names available within this servlet context

ServletContext getContext(java.lang.String uripath)

Returns a ServletContext object that corresponds to a specified URL on the server

java.lang.String getInitParameter(java.lang.String name)

Returns a String containing the value of the named context-wide initialization parameter, or returns null if the parameter does not exist

java.util.Enumeration getInitParameterNames()

Returns the names of the context initialization parameters as an Enumeration of String objects, or returns an empty Enumeration if the context has no initialization parameters

Servlet Scopes and Attributes

Let us look into the topics that will be covered under this section.

  • Servlet Attributes

  • Attribute-Specific Methods

Servlet Attributes

Attributes allow data to be stored and used in inter Servlet communication. The methods associated with attribute manipulation are:

Attribute

Scope of Data

ServletRequest

Duration of the request

HTTPSession

While the client is active

ServletContext

The life of Web Application

Attribute-Specific Methods

The table below has some of the functions mentioned.

public void setAttribute()

This method is used to set the given object in the application scope

getAttribute()

used to return the value of the attribute for the specified name

getInitParameterNames()

which is used to return the names of the context’s initialization parameter as an Enumeration.

removeAttributes():

used to remove that attribute with a given name from the Servlet context.

Servlet Collaboration

Let us understand the topics covered under this section.

  • What is Servlet Collaboration?
  • Ways of Servlet Collaboration
  • Forwarding and Redirecting
  • forward() method
  • include() method
  • RequestDispatcher Interface

Keen on learning more about Java Certification training? Get detailed info here!

What is Servlet Collaboration

The Servlet Collaboration involves sharing of information among multiple servlets.

Collaborating Servlets is passing common information that is to be shared directly by one Servlet to another Servlet of HTML or JSP through various invocations of methods.

Ways of Servlet Collaboration

There are various ways of Servlet Collaboration

  • Using RequestDispatcher include() and forward() method;
  • Using HTTPServletResponse sendRedirect() method;
  • Using ServletContext setAttribute() and getAttribute() methods;

Forwarding and Redirecting

Let us understand Forwarding and Redirecting below:

  • RequestDispatcher interface is used to forward request and response objects to another Servlet
  • The sendDirect method is used for Redirecting request and response objects
  • HTTPServletResponse has sendRedirect method; which is response.sendRedirect(“URL”) and provides the URL, where the user needs to be redirected.
  • HTTPServletRequest has getRequestDispatcher method that returns RequestDispatcher object
  • There are two methods, forward and include

forward() method

https://www.simplilearn.com/ice9/free_resources_article_thumb/forward-scope-method.JPG

  1. The client sends a request to Servlet 1.
  2. Servlet 1 can either forward the request to Servlet two or generate its response parallelly.
  3. Servlet two also generates a specific response.
  4. Both the responses are returned to the browser individually.

forward() method Syntax

RequestDispatcher= request. getRequestDispatcher(“url_pattern_for_servlet or HTML_file_name”);

rd.forward(request, response)

include() method

https://www.simplilearn.com/ice9/free_resources_article_thumb/include-scope-method.JPG

  1. The client sends a request to Servlet 1.
  2. Servlet 1 can either forward the request to Servlet two or generate its response parallelly.
  3. Servlet 2 also generates a specific response.
  4. Both the responses are returned to the browser as a single response.

include() method Syntax

RequestDispatcher rd= request.getRequestDispatcher(“url_pattern_for_servlet or HTML_file_name”);

rd.include(request, response);

Example: Login Screen

https://www.simplilearn.com/ice9/free_resources_article_thumb/request-dispatcher-interface.JPG

  1. We enter UserName and Password and Click Log In.

  2. Next, the validate Servlet checks if the information provided invalid.

  3. If it is valid; we move to the Welcome Servlet.

  4. If the validation fails; the response is included in the HTML file and sends back with a specific error message.

Summary

A quick summary of the various functions we have covered so far.

  • The requestDispatcher is an interface that is used to chain and called one Servlet from another or an HTML page from a Servlet.
  • The requestDispatcher will find the current request and response while chaining calls.
  • No new requests will be generated.
  • The Include method will include the current page along with the page mentioned in requestDispatcher configuration.
  • The Forward method displays only the URL mentioned in the requestDispatcher will be shown.

Key Takeaways

Let us quickly go through the topics we have covered so far in this tutorial.

  • Servlet is a java program that can perform dynamic operations and send to the web server. The web server then sends this response to the web client
  • The web container is built on top of the Java SE platform and implements the Servlet API and the service is required to process HTTP (and another TCP/IP requests).
  • The lifecycle of a Servlet is controlled by the web container in which the Servlet has been deployed.
  • Servlet API contains a number of classes and interfaces that define the contracts between a Servlet class and the runtime environment, provided for an instance by a confirming Servlet Container.
  • Collaborating Servlets is passing the common information that is to be shared directed by one Servlet to another Servlet of HTML or JSP through various invocations of the methods.

Conclusion

This covers the Java Servlet tutorial.

Find our Java Certification Training Online Classroom training classes in top cities:


Name Date Place
Java Certification Training 17 Aug -28 Sep 2019, Weekend batch Your City View Details
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Request more information

For individuals
For business
Name*
Email*
Phone Number*
Your Message (Optional)
We are looking into your query.
Our consultants will get in touch with you soon.

A Simplilearn representative will get back to you in one business day.

First Name*
Last Name*
Email*
Phone Number*
Company*
Job Title*