0% found this document useful (0 votes)
3 views26 pages

Introduction To Servlet

Servlets are Java-based server-side components that enhance web server functionality by processing requests and generating dynamic responses. They offer advantages such as portability, efficiency, and flexibility, and operate within a Java Virtual Machine. The document outlines servlet architecture, life cycle, API, and contrasts servlets with Common Gateway Interface (CGI) in terms of performance and resource management.

Uploaded by

Shankar Deva CSE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views26 pages

Introduction To Servlet

Servlets are Java-based server-side components that enhance web server functionality by processing requests and generating dynamic responses. They offer advantages such as portability, efficiency, and flexibility, and operate within a Java Virtual Machine. The document outlines servlet architecture, life cycle, API, and contrasts servlets with Common Gateway Interface (CGI) in terms of performance and resource management.

Uploaded by

Shankar Deva CSE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Introduction to Servlet

Servlets are protocol and platform independent server-side software components, written in Java. They
run inside a Java enabled server or application server, such as the WebSphere Application Server.
Servlets are loaded and executed within the Java Virtual Machine (JVM) of the Web server or
application server, in much the same way that applets are loaded and executed within the JVM of the
Web client. Since servlets run inside the servers, however, they do not need a graphical user interface
(GUI). In this sense, servlets are also faceless objects.

The Power of Servlets

What makes servlets a viable choice for web development? We believe that servlets offer a number of
advantages over other approaches, including: portability, power, efficiency, endurance, safety, elegance,
integration, extensibility, and flexibility.

What is Servlet

Servlets are small programs that execute on the server side of a Web connection and dynamically
extend the functionality of a Web server just as applets.

 Servlet is a technology which is used to create a web application.

 Servlet is an API that provides many interfaces and classes including documentation.

 Servlet is an interface that must be implemented for creating any Servlet.

 Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.

 Servlet is a web component that is deployed on the server to create a dynamic web page.

Servlet Architecture

The architecture, is the communication interface, protocol used, requirements of client and server, the
programming with the languages and software involved. Basically, it performs the below-mentioned
tasks.

1. The clients send the request to the webserver.

2. The web server receives the request.

3. The web server passes the request to the corresponding servlet.


4. The servlet processes the request and generates the response in the form of output.

5. The servlet sends the response back to the webserver.

6. The web server sends the response back to the client and the client browser displays it on the
screen.

Servlets more closely resemble Common Gateway Interface (CGI) scripts or programs than applets in
terms of functionality. As in CGI programs, servlets can respond to user events from an HTML request,
and then dynamically construct an HTML response that is sent back to the client.

Common Gateway Interface

The Common Gateway Interface (CGI) is the standard process that uses a set of rules to propagate the
user´s request to the web resources such as web server or web application program and respond to the
user through the web interface. CGI includes several working scripts and programs for web
communication. CGI is the mechanism that is part of the Hypertext Transport Protocol (HTTP). One of
the examples of CGI flow is the Web browsers send the forms data to the backend server, and CGI
connects to the application program on the web-server and the program response to the web browser.
CGI Architecture

Features of CGI

 It is a very well defined and supported standard.


 CGI scripts are generally written in either Perl, C, or maybe just a simple shell script.
 CGI is a technology that interfaces with HTML.
 CGI is the best method to create a counter because it is currently the quickest
 CGI standard is generally the most compatible with today´s browsers

Advantages of CGI

 The advanced tasks are currently a lot easier to perform in CGI than in Java.
 It is always easier to use the code already written than to write your own.
 CGI specifies that the programs can be written in any language, and on any platform, as long as
they conform to the specification.
 CGI-based counters and CGI code to perform simple tasks are available in plenty.

Disadvantages of CGI

 In Common Gateway Interface each page load incurs overhead by having to load the programs
into memory.
 Generally, data cannot be easily cached in memory between page loads.
 There is a huge existing code base, much of it in Perl.
 CGI uses up a lot of processing time.
Common Gateway Interface(CGI) vs Servlet

Common Gateway Interface


The Common Gateway Interface (CGI) provides the middleware between servers and external
databases or information sources. The Web server typically passes the form information to a small
application program that processes the data and may send back a confirmation message. This process or
convention for passing data back and forth between the server and the application is called the common
gateway interface. The following image describes how a web server acts as an intermediate between the
CGI program and the client browser.

A new process is started for each client request. The creation of the process for every such request
requires time and significant server resources which limits the number of requests a server can handle

Servlet

Servlets are server based java application that can link directly to the Web server. Servlets are thread
based applications and work on server level and they share data among each other. All the programs of
Servlets are written in JAVA and they get to run on JAVA Virtual Machine. The following image
describes how a request from clients is served with the help of threads:
CGI Servlet

The CGI programs are written in native OS. Servlet is written in java class & its runs in JVM.

CGI creates a process base for each request. Servlet creates a new thread to process each
request.

The CGI is a language-independent interface The main purpose of servlets is to add up the
that allows a server to start an external process. functionality to
a web server.

A CGI program needs to be loaded and started Servlets stay in the memory while serving the
on each CGI request. requests.

CGI is not able to read the HTTP servers. Servlets are useful to read and set the HTTP
servers.

CGI are plateform dependent. Servlets are plateform independent.

Servlets are more secure and useful for Data CGI is less secure and is not useful for data sharing.
sharing.
Servlet Life Cycle

Three methods are central to the life cycle of a servlet. These are init( ), service( ), and destroy( ).
They are implemented by every servlet and are invoked at specific times by the server.

 First, assume that a user enters a Uniform Resource Locator (URL) to a Web browser. The browser
then generates an HTTP request for this URL. This request is then sent to the appropriate server.

 Second, this HTTP request is received by the Web server. The server maps this request to a
particular servlet. The servlet is dynamically retrieved and loaded into the address space of the
server.

 Third, the server invokes the init( ) method of the servlet. This method is invoked only when the
servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it
may configure itself.

 Fourth, the server invokes the service( ) method of the servlet. This method is called to process the
HTTP request. You will see that it is possible for the servlet to read data that has been provided in
the HTTP request. It may also formulate an HTTP response for the client.

 The servlet remains in the server’s address space and is available to process any other HTTP
requests received from clients. The service( ) method is called for each HTTP request.

 Finally, the server may decide to unload the servlet from its memory. The algorithms by which this
determination is made are specific to each server. The server calls the destroy() method to
relinquish any resources such as file handles that are allocated for the servlet. Important data may
be saved to a persistent store. The memory allocated for the servlet and its objects can then be
garbage collected.
Servlet API

To create Java Servlets, we need to use Servlet API which contains all the necessary interfaces and
classes. Servlet API has 2 packages namely

 javax.servlet

 javax.servlet.http

javax.servlet

This package support Generic servlet which is protocol independent. These interfaces and classes
describe and define the contracts between a servlet class and the runtime environment provided by a
servlet container.

Classes available in javax.servlet package

Classes Description

GenericServlet Defines a generic, protocol-independent servlet.

ServletInputStream Provides an input stream for reading binary data from a client
request, including an efficient readLine method for reading data
one line at a time.

ServletOutputStream Provides an output stream for sending binary data to the client.

ServletContextEvent This is the event class for notifications about changes to the servlet
context of a web application.

ServletContextAttributeEvent This is the event class for notifications about changes to the
attributes of the servlet context of a web application.

ServletRequestEvent Events of this kind indicate lifecycle events for a ServletRequest.

ServletRequestAttributeEvent This is the event class for notifications of changes to the attributes
of the servlet request in an application.
Interface available in javax.servlet package

Interface Description

Servlet Defines methods that all servlets must implement.

ServletConfig A servlet configuration object used by a servlet container to pass information


to a servlet during initialization.

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.

ServletRequest Defines an object to provide client request information to a servlet.

ServletResponse Defines an object to assist a servlet in sending a response to the client.

RequestDispatcher Defines an object that receives requests from the client and sends them to any
resource (such as a servlet, HTML file, or JSP file) on the server.

javax.servlet.http

This package describe and 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.

Classes available in javax.servlet package

Classes Description

Cookie Creates a cookie, a small amount of information sent by a servlet to


a Web browser, saved by the browser, and later sent back to the
server.

HttpServlet Provides an abstract class to be subclassed to create an HTTP


servlet suitable for a Web site.

HttpServletRequestWrapper Provides a convenient implementation of the HttpServletRequest


interface that can be subclassed by developers wishing to adapt the
request to a Servlet.
Classes Description

HttpServletResponseWrapper Provides a convenient implementation of the HttpServletResponse


interface that can be subclassed by developers wishing to adapt the
response from a Servlet.

HttpSessionBindingEvent Events of this type are either sent to an object that implements
HttpSessionBindingListener when it is bound or unbound from a
session, or to a HttpSessionAttributeListener that has been
configured in the deployment descriptor when any attribute is
bound, unbound or replaced in a session.

HttpSessionEvent This is the class representing event notifications for changes to


sessions within a web application.

Interface available in javax.servlet package

Interface Description

HttpServletRequest Extends the ServletRequest interface to provide request information


for HTTP servlets.

HttpServletResponse Extends the ServletResponse interface to provide HTTP-specific


functionality in sending a response.

HttpSession Provides a way to identify a user across more than one page request or
visit to a Web site and to store information about that user.

HttpSessionActivationListener Objects that are bound to a session may listen to container events
notifying them that sessions will be passivated and that session will be
activated.

HttpSessionAttributeListener This listener interface can be implemented in order to get notifications


of changes to the attribute lists of sessions within this web application.

HttpSessionBindingListener Causes an object to be notified when it is bound to or unbound from a


session.

HttpSessionListener Implementations of this interface are notified of changes to the list of


active sessions in a web application.
Creating and Running a Servlet Program

Steps for creating and running a servlet

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server
6. Access the servlet

Create a directory structure

The directory structure defines that where to put the different types of files so that web container may
get the information and respond to the client.

Create a Servlet

The servlet example can be created by three ways:


1) By implementing Servlet interface,
2) By inheriting GenericServlet class, (or)
3) By inheriting HttpServlet class

NOTE: The mostly used approach is by extending HttpServlet because it provides http request
HelloWorld.java

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
}
Note: HttpServlet contains all the life cycle methods of Servlet and the service() method is writen in the
following two methods, they are
public void doGet (HttpServletRequest, HttpServletResponse) throws ServletException,
IOException
public void doPost (HttpServletRequest, HttpServletResponse) throws ServletException,
IOException

Compile the Servlet

To compile the servlet program we have to set a CLASSPATH

..\tomcat\lib\servlet-api.jar

Now compile the HelloWorld.java using following command

javac HelloWorld.java

If the compilation is successfull then HelloWorld.class file will be generated. Copy *.class file into
document root/WEB-INF/classes folder
Create a deployment descriptor

1. Whenever client makes a request to a servlet that request is received by server and server goes to a
predefined file called web.xml for the details about a servlet.
2. web.xml file always gives the details of the servlets which are available in the server.
3. If the requested servlet is available in web.xml then server will go to the servlet, executes the servlet
and gives response back to client.
4. If the server is not able to find the requested servlet by the client then server generates an error
(resource not found).

web.xml

<web-app>
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/servletdemo</url-pattern>
</servlet-mapping></web-app>

Start the server

To start Apache Tomcat server, double click on the startup.bat available at ../tomcat/bin directory.

Access the servlet

Open broser and write http://hostname:portno/contextroot/url-pattern. For example:

http://localhost:8080/studyglance/servletdemo
Reading Form Parameters in Servlet

Servlets parse the form(client) data automatically using the following methods depending on the
situation −
getParameter() − You call request.getParameter() method to get the value of a form parameter.
getParameterValues() − Call this method if the parameter appears more than once and returns multiple
values, for example checkbox.
getParameterNames() − Call this method if you want a complete list of all parameters in the current
request

Client pass some information from browser to web server uses GET Method or POST Method.

If a client send the data to the servlet, that data will be available in the object of HttpServletRequest
interface. In case of getParameter() method we have to pass input parameter name and it will give the
value.

request.getParameter("name")

If you are not aware of input parameter name? or if you have more input values its really tedious to use
getParameter() method so we use getParameterNames(). This method returns an Enumeration that
contains the parameter names in an unspecified order. Once we have an Enumeration, we can loop
down the Enumeration in standard way by, using hasMoreElements() method to determine when to stop
and using nextElement() method to get each parameter name.

Enumeration en=request.getParameterNames();while(en.hasMoreElements()){
String param_name = (String) en.nextElement();
String value=request.getParameter(param_name);
.......}

login.html

<html lang="en">
<head>
<title>Login page</title>
</head>
<body>
<h1> Login Form </h1>
<form method="post" action="login">
Username: <input type="text" name="username">
Password: <input type="password" name="pass">
</form>
</body></html>

LoginDemo.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class LoginDemo extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("username"); //will return value
out.println("Welcome "+name);
out.close()
}
}

web.xml

<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
Reading Initialization Parameters in Servlet

Both ServletContext and ServletConfig are basically the configuration objects which are used by the
servlet container to initialize the various parameter of a web application. But they have some difference
in terms of scope and availability.

Difference between ServletConfig vs. ServletContext

ServletConfig ServletContext

ServletConfig object is one per servlet class. ServletContext object is global to the entire web
application.

Object of ServletConfig will be created during the Object of ServletContext will be created at the
initialization process of the servlet. time of web application deployment

We have to give the request explicitly in order to ServletContext object can be available even
create the ServletConfig object for the first time. before giving the first request.

Scope: As long as a servlet is executing, the Scope: As long as a web application is executing,
ServletConfig object will be available, it will be the ServletContext object will be available, and it
destroyed once the servlet execution is completed. will be destroyed once the application is
removed from the server.

ServletConfig object is used while only one ServletContext object is used while application
servlet requires information shared by it. requires information shared by it.

getServletConfig() method is used to obtain getServletContext() method is used to obtain


Servletconfig object. ServletContext object.

In web.xml — tag will be appear under tag. In web.xml — tag will be appear under tag.

ServletConfig

An object of ServletConfig is created by the web container for each servlet. This object can be used to
get configuration information from web.xml file. If the configuration information is modified from the
web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any
specific content is modified from time to time.
Methods of ServletConfig interface

public String getInitParameter(String name): Returns the parameter value for the specified
parameter name.
public Enumeration getInitParameterNames(): Returns an enumeration of all the initialization
parameter names.
public String getServletName(): Returns the name of the servlet

web.xml

<web-app>
<servlet>
<servlet-name>Config</servlet-name>
<servlet-class>ConfigDemo</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>studyglance</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Config</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

ConfigDemo.java

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class ConfigDemo extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();

//get ServletConfig object.


ServletConfig config=getServletConfig();

//get init parameter from ServletConfig object.


String name= config.getInitParameter("username");
out.println("Welcome "+name);
out.close()
}
}

ServletContext

ServletContext object can be used to get configuration information from web.xml file. There is only
one ServletContext object per web application. If any information is shared to many servlet, it is better
to provide it from the web.xml file using the element.

Methods commonly used in ServletContext interface

public String getInitParameter(String name):Returns the parameter value for the specified parameter
name.
public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters.
public void setAttribute(String name,Object object):sets the given object in the application scope.
public Object getAttribute(String name):Returns the attribute for the specified name.

web.xml

<web-app>
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<servlet>
<servlet-name>Context</servlet-name>
<servlet-class>ContextDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Context</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

ConfigDemo.java

// Import required java libraries


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class ContextDemo extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
//get ServletContext object.
ServletContext context=getServletContext();

//get init parameter from ServletConfig object.


String driverName= context.getInitParameter("driver");
out.println("driver name is = "+driverName);
out.close()
}}
Session Tracking in Servlet

Session tracking is a mechanism that servlets use to maintain state about a series of requests from the
same user (that is, requests originating from the same browser) across some period of time. It is also
known as session management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time
user requests to the server, server treats the request as the new request. So we need to maintain the state
of an user to recognize to particular user.

Session Tracking Techniques

There are four techniques used in Session tracking:

1. Hidden Form Field

2. URL Rewriting

3. Cookies

4. HttpSession

Hidden Form Field

In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user.

In such case, we store the information in the hidden field and get it from another servlet. This approach
is better if we have to submit form in all the pages and we don't want to depend on the browser.

<input type="hidden" name="uname" value="Studyglance">

Advantage of Hidden Form Field


It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:


1. It is maintained at server side.
2. Extra form submission is required on each pages.
3. Only textual information can be used.

URL Rewriting

In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource.
We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&?

A name and a value is separated using an equal = sign, a parameter name/value pair is separated from
another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to
obtain a parameter value.

Advantage of URL Rewriting


1. It will always work whether cookie is disabled or not (browser independent).
2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting


1. It will work only with links.
2. It can send Only textual information.

Cookies in Servlet

A cookie is a piece of data from a website that is stored within a web browser(Client side) that the
website can retrieve at a later time. Cookies are used to tell the server that users have returned to a
particular website.

How cookies work

When you send a request to the server, the server sends a reply in which it embeds the cookie which
serves as an identifier to identify the user. So, next time when you visit the same website, the cookie
lets the server know that you are visiting the website again.

Cookies Used For?

Session management. For example, cookies let websites recognize users and recall their individual
login information and preferences, such as sports news versus politics.

Personalization. Customized advertising is the main way cookies are used to personalize your sessions.
You may view certain items or parts of a site, and cookies use this data to help build targeted ads that
you might enjoy.

Tracking. Shopping sites use cookies to track items users previously viewed, allowing the sites to
suggest other goods they might like and keep items in shopping carts while they continue shopping.

Commonly used Methods in Cookie

public String getName( ) Returns the name of the cookies.


public String getPath( ) Returns the path of the server to which the browser returns the cookie.
public String getValue( ) Returns the value of the cookie.
public int getMaxAge( ) Returns the maximum age limit to the cookie, specified in seconds.
public void setMaxAge(int expiry) Sets the maximum age of the cookies in seconds.
public void setValue(String newValue) Allocates a new value to a cookie after the cookie is created.

Create a Cookie Object

The constructor of Cookie class creates the cookie object with corresponding cookie name and value.

//creating cookie object Cookie cookie = new Cookie("username","Studyglance");


//adding cookie to the responseResponse.addCookie(cookie);

Get Cookie from client request

Cookie ck[ ]=request.getCookies();

cookiedemo.html

<html>
<head>
<title>Cookie Demo</title>
</head>
<body>
<form action="servlet1" method="post">
Enter Your Name:<input type="text" name="userName"/><br/><br/>
<input type="submit" value="SUBMIT"/>
</form>
</body>
</html>

SetCookieServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
//creating cookie object
Cookie ck=new Cookie("uname",name);
//adding cookie in the response
response.addCookie(ck);
out.print("Cookie Saved");
//creating submit button
out.print("<br><form action='servlet2' method='post'>");
out.print("<input type='submit' value='View the cookie value'>");
out.print("</form>");
out.close();
}
catch(Exception e){
System.out.println(e);
}
}}

GetCookieServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.println("<h3>Reading the cookies</h3>");
out.println("<br/>");
out.println("Name of the cookie : " + ck[0].getName() + "<br/>");
out.println("Value in cookie : " + ck[0].getValue());
out.close();
}catch(Exception e){
System.out.println(e);
}
}}
web.xml

<web-app>
<servlet>
<servlet-name>set</servlet-name>
<servlet-class>SetCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>set</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>get</servlet-name>
<servlet-class>GetCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>

HTTPSession in Servlet

A session contains information specific to a particular user across the whole application. When a user
enters into a website (or an online application) for the first time HttpSession is obtained via
request.getSession(), the user is given a unique ID to identify his session.

The HttpSession stays alive until it has not been used for more than the timeout value specified in tag in
deployment descriptor file( web.xml). The default timeout value is 30 minutes, this is used if you don’t
specify the value in tag. This means that when the user doesn’t visit web application time specified, the
session is destroyed by servlet container. The subsequent request will not be served from this session
anymore, the servlet container will create a new session.

Commonly used Methods of Servlet HttpSession

setAttribute(String name, Object value): Binds an object to this session, using the name specified.
setMaxInactiveInterval(int interval): Specifies the time, in seconds, between client requests before
the servlet container will invalidate this session.
getAttribute(String name): Returns the object bound with the specified name in this session, or null if
no object is bound under the name.
getAttributeNames(): Returns an Enumeration of String objects containing the names of all the objects
bound to this session.
getId(): Returns a string containing the unique identifier assigned to this session.
invalidate(): Invalidates this session then unbinds any objects bound to it.
removeAttribute(String name): Removes the object bound with the specified name from this session.

sessionemo.html

<html>
<head>
<title>session Demo</title>
</head>
<body>
<form action="servlet1" method="post">
Enter Your Name:<input type="text" name="userName"/><br/><br/>
<input type="submit" value="SUBMIT"/>
</form>
</body>
</html>

SetSessionServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetSessionServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
// Create a session object.
HttpSession session = request.getSession(true);

session.setAttribute("uname",name);
//creating submit button
out.print("<br><form action='servlet2' method='post'>");
out.print("<input type='submit' value='View the session'>");
out.print("</form>");
out.close();
}
catch(Exception e){
System.out.println(e);
}
}}

GetSessionServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetSessionServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String name=(String)session.getAttribute("uname");
out.print("Hello!.. Welcome "+name);
out.close();
}catch(Exception e){
System.out.println(e);
}
}}

web.xml

<web-app>
<servlet>
<servlet-name>set</servlet-name>
<servlet-class>SetSessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>set</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>get</servlet-name>
<servlet-class>GetSessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>get</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping> </web-app>

You might also like