SlideShare a Scribd company logo
State management
Http protocol that is used for communication between client and web server
is a stateless protocol that is for each request new HTTP connection is
established between client and server.
The disadvantage of stateless protocol is that server fails to recognize that a
series of request submitted by a user or logically related and represent a
single task form end user prospective.
Problem of state management deals with the maintenance of state over
the stateless protocol.
Following use case explains the problem of state management:
Example 1- program ServletContext object is used for state management.
Program save with Name: index.html
<html>
<head><title>Inter Application Forwarding..</title></head>
<body>
<form method="get" action="welcomeServlet">
Name :<input type="text" name="txtName"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Program save with Name: WelcomeServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String name=request.getParameter("txtName");
PrintWriter out=response.getWriter();
out.println("<b> Welcome, "+name+"</b>");
ServletConfig cnf=getServletConfig();
ServletContext ctx=cnf.getServletContext();
ctx.setAttribute("user",name);
out.println("<br> <form action=tourServlet method=get>");
out.println("<br><input type=submit value="Take a Tour "></form>" );
out.close();
}
}
Program save with Name: TourServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class TourServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
ServletConfig cnf=getServletConfig();
ServletContext ctx=cnf.getServletContext();
String name=(String)ctx.getAttribute("user");
PrintWriter out=response.getWriter();
out.println("<b> Sorry, "+name+"</b>");
out.println("<br>Site is down for routine maintenance, vist again later..");
out.close();
}
}
Program save with Name: web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>welcomeServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>TourServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>tourServlet</url-pattern>
</servlet-mapping>
</web-app>
Output :
Run program on two browser and test with both users one by one
Yes This is not complete solution of state management so there is requirement of another
technique.
Problem with ServletContext object when we use it for state management:
Name of user is user specific which must not be store in ServletContext because other user
is override it.
Note: In ServletContext store only application specific data not store user specific data.
Following solution is device to solve the problem of State
management:
1- Cookies
2- Hidden form fields
3- URL rewriting
4- HttpSession object
1- Cookies
A cookie represent information in the form of key value pair which is send by the
server as part of response and is submitted by the browser to the server as part of
the sub sequent request.
Cookie provides a simple mechanism of maintaining user information between
multiple requests.
Cookie can be of 2 types:
1- Persistent cookies
2- Non Persistent cookies
1- Persistent cookies:
Persistent cookies remain valid for multiple sessions.
They are store by the browser in a text file on the client machine to be use
again and again.
2- Non Persistent cookies:
Non persistence cookies remain valid only for a
single session, they are store in the browser cache during the session and
discarded by the browser when the session is complete.
Note: By default all cookies are non persistent.
Advantage:
1- Simplicity is main advantage of this approach.
Disadvantage:
1- This method of state maintenance is browser dependent.
2- Only textual information can be persisted between request (Object Map,
File are not persisted in cookies).
3- Persistent cookies do not differentiate users on the machine.
Note: Netscape first introduce cookies.
javax.servlet.http.Cookie, class provides object representation of cookies.
Cookies object can be created using following constructor:
public Cookie(String name, String value);
Method of Cookie class:
1- getName():
Is use to obtain the name of the cookie.
public String getName();
2- getValue():
Is use to obtain the value of the cookie.
public String getValue();
3- setMaxAge():
Is use to specify the time for which cookie remain valid.
This method makes cookies persistent.
public void setMaxAge(int seconds);
etc…
addCookie():
Method of HttpServletResponse interface is used to add
the cookie as a part of the response.
public void addCookie(Cookie ck);
getCookies():
Method of HttpServletRequest interface is used to
obtain the cookies which are submitted as part of the request.
public Cookie[] getCookies();
Example 1- program for state management using Cookies.
Program save with Name: index.html
<html>
<head><title>Inter Application Forwarding..</title></head>
<body>
<form method="get" action="welcomeServlet">
Name :<input type="text" name="txtName"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Program save with Name: WelcomeServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String name=request.getParameter("txtName");
PrintWriter out=response.getWriter();
out.println("<b> Welcome, "+name+"</b>");
Cookie ck=new Cookie("user",name);
response.addCookie(ck);
ck.setMaxAge(60); // for making Persisted Cookies
out.println("<br> <form action=tourServlet method=get>");
out.println("<br><input type=submit value="Take a Tour"></form>" );
out.close();
}
}
Program save with Name: TourServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class TourServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String name="Gust";
Cookie ch[]=request.getCookies();
if(ch!=null)
name=ch[0].getValue();
out.println("<b> Sorry, "+name+"</b>");
out.println("<br>Site is down for routine maintenance, vist again later..");
out.close();
}
}
Program save with Name: web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>welcomeServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>TourServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>tourServlet</url-pattern>
</servlet-mapping>
</web-app>
Output :
Run program on two browser and test with both users one by one
Yes, now state is managed it will give correct output.
2- Hidden form field
Hidden form field provide the browser independent
method of maintaining state between requests. In this method information is
to persistence between one request to another is contain in invisible text
field which are added to the response page whenever a new request is
submitted using the response page value of invisible field are posted as
request parameter.
Limitation:
1- Only textual information can be persisted between requests.
2- This approach can only be used when request is submitted using the form
of response page that is this approach does not work with hyperlink.
Example 1- program for state management using Hidden form field.
Program save with Name: index.html
<html>
<head><title>Inter Application Forwarding..</title></head>
<body>
<form method="get" action="welcomeServlet">
Name :<input type="text" name="txtName"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Program save with Name: WelcomeServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String name=request.getParameter("txtName");
PrintWriter out=response.getWriter();
out.println("<b> Welcome, "+name+"</b>");
out.println("<br> <form action=tourServlet method=get>");
out.println("<br><input type=hidden name=txtHidden
value=""+name+"">");
out.println("<br><input type=submit value="Take a Tour"></form>" );
out.close();
}
}
Program save with Name: TourServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class TourServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String name=request.getParameter("txtHidden");
out.println("<b> Sorry, "+name+"</b>");
out.println("<br>Site is down for routine maintenance, vist again later..");
out.close();
}
}
Program save with Name: web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>welcomeServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>TourServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>tourServlet</url-pattern>
</servlet-mapping>
</web-app>
Output :
Run program on two browser and test with both users one by one
Yes, now state is managed it will give correct output.
3- URL rewriting (mostly used)
In this approach information to be persisted between request is dynamically
appended to the URL in response page, whenever a request is submitted
using these URL, append information is submitted as request parameters.
Syntax of appending:
URL?paramName=value & paramName=value
Limitation:
1- Only textual information can be persisted using this approach.
2- In case of input form this approach work only if post request is submitted
(Because get request changed the URL).
Example 1- program for state management using URL rewriting (Using Form
Field).
Program save with Name: index.html
<html>
<head><title>Inter Application Forwarding..</title></head>
<body>
<form method="get" action="welcomeServlet">
Name :<input type="text" name="txtName"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Program save with Name: WelcomeServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String name=request.getParameter("txtName");
PrintWriter out=response.getWriter();
out.println("<b> Welcome, "+name+"</b>");
out.println("<br> <form method=post action="tourServlet?userName="+name+"">");
out.println("<br><input type=submit value="Take a Tour"></form>" );
out.close();
}
}
Program save with Name: TourServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class TourServlet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String name=request.getParameter("userName");
if(name.equals(""))
name="Gust";
out.println("<b> Sorry, "+name+"</b>");
out.println("<br>Site is down for routine maintenance, vist again later..");
out.close();
}
}
Program save with Name: web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>welcomeServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>TourServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>tourServlet</url-pattern>
</servlet-mapping>
</web-app>
Output :
In this program we are using post method for submitting request on tourServlet that help
URL is overridden that is specified in program and if we using get request then new URL is
created instead of specified in program.
If we try to use get method then NullPointerException occure.
Example 1- program for state management using URL rewriting (Using Hyperlink).
Program save with Name: index.html
<html>
<head><title>Inter Application Forwarding..</title></head>
<body>
<form method="get" action="welcomeServlet">
Name :<input type="text" name="txtName"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Program save with Name: WelcomeServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String name=request.getParameter("txtName");
PrintWriter out=response.getWriter();
out.println("<b> Welcome, "+name+"</b>");
out.println("<br><a href="tourServlet?userName="+name+"">Take a
Tour</a>");
out.close();
}
}
Program save with Name: TourServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class TourServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String name=request.getParameter("userName");
if(name.equals(""))
name="Gust";
out.println("<b> Sorry, "+name+"</b>");
out.println("<br>Site is down for routine maintenance, vist again later..");
out.close();
}
}
Program save with Name: web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>welcomeServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>TourServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>tourServlet</url-pattern>
</servlet-mapping>
</web-app>
Output :
In this program use get method because Hyperlink is generate get request.
4- HttpSession
javax.servlet.http.HttpSession is an interface of Servlet API.
Implementation of which is provided by the vendors. An object of type
HttpSession can be get created by the web server per user. This object is
used by the application developer to store user information between
requests.
Commonly used method of HttpSession interface:
1- setAttribute():
Is used to store an attribute in the session scope.
public void setAttribute(String name, Object value);
2- getAttribute():
Is used to obtain an attribute from the session scope.
public Object getAttribute(String name);
3- getAttributeNames():
Is used to find out the names of attributes saved in
session scope.
public Enumeration getAttributeNames();
4- removeAttribute():
Is used to remove an attributes from the session scope.
public boolean removeAttribute(String name);
Methods used For management Session Object:
5- isNew():
Is used to find out whether session is created for the current
request or not.
public boolean isNew();
6- setMaxInactiveInterval():
Is used to specify the time for which a session remains valid
even if no request is received from the client.
public void setMaxInactiveInterval(int second);
7-invalidate():
Is used to release a session.
public void invalidate();
etc…..
getSession():
getSession() method of HttpServletRequest interface is used
to obtain a HttpSession object.
public HttpSession getSession();
public HttpSession getSession(boolean createFlag);
Example 1- program for state management using HttpSession object.
Program save with Name: index.html
<html>
<head><title>Inter Application Forwarding..</title></head>
<body>
<form method="get" action="welcomeServlet">
Name :<input type="text" name="txtName"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Program save with Name: WelcomeServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String name=request.getParameter("txtName");
PrintWriter out=response.getWriter();
out.println("<b> Welcome, "+name+"</b>");
HttpSession session=request.getSession();
session.setAttribute("uname",name);
session.setMaxInactiveInterval(3); // If user is ideal state max(3 second)
then
// Session object is destroyed.
out.println("<br><a href=" tourServlet ">Take a Tour</a>");
out.close();
}
}
Program save with Name: TourServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class TourServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
HttpSession session=request.getSession();
String name=(String)session.getAttribute("uname");
// session.invalidate(); // Use for destroy Session object.
if(name==null)
name="Guest";
out.println("<b> Sorry, "+name+"</b>");
out.println("<br>Site is down for routine maintenance, vist again later..");
out.close();
}
}
Program save with Name: web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>welcomeServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>TourServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>tourServlet</url-pattern>
</servlet-mapping>
</web-app>
Output :
Run program and test it frequently submitting request and wait 3 second then submit
request.
Yes, now state is managed it will give correct output.
In order to manage session object web server create unique id for each
session. Session object are store in a map by the server using the id as key.
Unique identifier for each session is sent with the response in the form of
cookies or request parameter using URL rewriting.
When subsequent request are submitted session id is made available which
is used by the server to identify the session.

More Related Content

What's hot

JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Introduction to EJB
Introduction to EJBIntroduction to EJB
Introduction to EJB
Return on Intelligence
 
Unit1 2 Webtechnology
Unit1 2 WebtechnologyUnit1 2 Webtechnology
Unit1 2 Webtechnology
Abhishek Kesharwani
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Scripting Languages
Scripting LanguagesScripting Languages
Scripting Languages
Forrester High School
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJBEnterprise Java Beans - EJB
Enterprise Java Beans - EJB
Peter R. Egli
 
Event Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdfEvent Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdf
AliEndris3
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
DivyanshGupta922023
 
Web Application Introduction
Web Application  IntroductionWeb Application  Introduction
Web Application Introduction
shaojung
 
Jsp
JspJsp
Jsp lifecycle
Jsp   lifecycleJsp   lifecycle
Jsp lifecycle
chauhankapil
 
Basic knowledge on html and dhtml
 Basic knowledge on html and dhtml Basic knowledge on html and dhtml
Basic knowledge on html and dhtml
Suryakanta Behera
 
Hostel Management system Report
Hostel Management system ReportHostel Management system Report
Hostel Management system Report
Prasoon Rawat
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVA
Jalpesh Vasa
 
Software Process Models
Software Process ModelsSoftware Process Models
Software Process Models
Hassan A-j
 

What's hot (20)

JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Introduction to EJB
Introduction to EJBIntroduction to EJB
Introduction to EJB
 
Unit1 2 Webtechnology
Unit1 2 WebtechnologyUnit1 2 Webtechnology
Unit1 2 Webtechnology
 
Acknowledgement
AcknowledgementAcknowledgement
Acknowledgement
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Introduction to .NET Framework
Introduction to .NET FrameworkIntroduction to .NET Framework
Introduction to .NET Framework
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
ASP.NET Basics
ASP.NET Basics ASP.NET Basics
ASP.NET Basics
 
Scripting Languages
Scripting LanguagesScripting Languages
Scripting Languages
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJBEnterprise Java Beans - EJB
Enterprise Java Beans - EJB
 
Event Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdfEvent Driven programming(ch1 and ch2).pdf
Event Driven programming(ch1 and ch2).pdf
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
Web Application Introduction
Web Application  IntroductionWeb Application  Introduction
Web Application Introduction
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
 
Jsp
JspJsp
Jsp
 
Jsp lifecycle
Jsp   lifecycleJsp   lifecycle
Jsp lifecycle
 
Basic knowledge on html and dhtml
 Basic knowledge on html and dhtml Basic knowledge on html and dhtml
Basic knowledge on html and dhtml
 
Hostel Management system Report
Hostel Management system ReportHostel Management system Report
Hostel Management system Report
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVA
 
Software Process Models
Software Process ModelsSoftware Process Models
Software Process Models
 

Viewers also liked

Dr. Becky R. Batteen-Resume-2016
Dr. Becky R. Batteen-Resume-2016Dr. Becky R. Batteen-Resume-2016
Dr. Becky R. Batteen-Resume-2016Dr Becky Batteen
 
Robin.Graff resume
Robin.Graff resumeRobin.Graff resume
Robin.Graff resumeRobin Graff
 
Pad sintang
Pad sintangPad sintang
Pad sintang
Harry Calbara
 
Протокол № 16-15ок заседания Комиссии по вопросам градостроительства, землепо...
Протокол № 16-15ок заседания Комиссии по вопросам градостроительства, землепо...Протокол № 16-15ок заседания Комиссии по вопросам градостроительства, землепо...
Протокол № 16-15ок заседания Комиссии по вопросам градостроительства, землепо...
Дарья Каштанова
 
Towards a more dynamic Museu Picasso Barcelona through the web 2.0
Towards a more dynamic Museu Picasso Barcelona through the web 2.0Towards a more dynamic Museu Picasso Barcelona through the web 2.0
Towards a more dynamic Museu Picasso Barcelona through the web 2.0Jacqueline Glarner
 
PCAST Talk 2011
PCAST Talk 2011PCAST Talk 2011
PCAST Talk 2011
Ashwin Ram
 
How can we rely upon Social Network Measures? Agent-base modelling as the nex...
How can we rely upon Social Network Measures? Agent-base modelling as the nex...How can we rely upon Social Network Measures? Agent-base modelling as the nex...
How can we rely upon Social Network Measures? Agent-base modelling as the nex...
Bruce Edmonds
 
Simulating Superdiversity
Simulating Superdiversity Simulating Superdiversity
Simulating Superdiversity
Bruce Edmonds
 
Clean india campaign
Clean india campaignClean india campaign
Clean india campaign
Akash Molla
 
Peter Opsvik's Philosophy of Sitting
Peter Opsvik's Philosophy of SittingPeter Opsvik's Philosophy of Sitting
Peter Opsvik's Philosophy of Sitting
Ergomonkey
 

Viewers also liked (11)

Dr. Becky R. Batteen-Resume-2016
Dr. Becky R. Batteen-Resume-2016Dr. Becky R. Batteen-Resume-2016
Dr. Becky R. Batteen-Resume-2016
 
Robin.Graff resume
Robin.Graff resumeRobin.Graff resume
Robin.Graff resume
 
Pad sintang
Pad sintangPad sintang
Pad sintang
 
Протокол № 16-15ок заседания Комиссии по вопросам градостроительства, землепо...
Протокол № 16-15ок заседания Комиссии по вопросам градостроительства, землепо...Протокол № 16-15ок заседания Комиссии по вопросам градостроительства, землепо...
Протокол № 16-15ок заседания Комиссии по вопросам градостроительства, землепо...
 
Towards a more dynamic Museu Picasso Barcelona through the web 2.0
Towards a more dynamic Museu Picasso Barcelona through the web 2.0Towards a more dynamic Museu Picasso Barcelona through the web 2.0
Towards a more dynamic Museu Picasso Barcelona through the web 2.0
 
PCAST Talk 2011
PCAST Talk 2011PCAST Talk 2011
PCAST Talk 2011
 
How can we rely upon Social Network Measures? Agent-base modelling as the nex...
How can we rely upon Social Network Measures? Agent-base modelling as the nex...How can we rely upon Social Network Measures? Agent-base modelling as the nex...
How can we rely upon Social Network Measures? Agent-base modelling as the nex...
 
Simulating Superdiversity
Simulating Superdiversity Simulating Superdiversity
Simulating Superdiversity
 
Clean india campaign
Clean india campaignClean india campaign
Clean india campaign
 
Deut ppt-017
Deut ppt-017Deut ppt-017
Deut ppt-017
 
Peter Opsvik's Philosophy of Sitting
Peter Opsvik's Philosophy of SittingPeter Opsvik's Philosophy of Sitting
Peter Opsvik's Philosophy of Sitting
 

Similar to State management servlet

Asp.net
Asp.netAsp.net
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
Divyam Pateriya
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
Jayaprasanna4
 
Documentation
DocumentationDocumentation
DocumentationKalyan A
 
Session and state management
Session and state managementSession and state management
Session and state management
Paneliya Prince
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
Tanmoy Barman
 
Play framework
Play frameworkPlay framework
Play framework
Keshaw Kumar
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
Techglyphs
 
Student_result_management_system_project.doc
Student_result_management_system_project.docStudent_result_management_system_project.doc
Student_result_management_system_project.doc
AnshChhabra6
 
State management in asp
State management in aspState management in asp
State management in asp
Ibrahim MH
 
Lecture 10.pptx
Lecture 10.pptxLecture 10.pptx
Lecture 10.pptx
Javaid Iqbal
 
Android Trainning Session 2
Android Trainning  Session 2Android Trainning  Session 2
Android Trainning Session 2
Shanmugapriya D
 
GAP
GAPGAP
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - Java
JainamParikh3
 
GAP A Tool for Visualize Web Site in Heterogeneus Mobile Devices
GAP A Tool for Visualize Web Site in Heterogeneus Mobile DevicesGAP A Tool for Visualize Web Site in Heterogeneus Mobile Devices
GAP A Tool for Visualize Web Site in Heterogeneus Mobile Devices
Juan Carlos Olivares Rojas
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
vinoth ponnurangam
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3
sandeep54552
 
ASP.NET Lecture 2
ASP.NET Lecture 2ASP.NET Lecture 2
ASP.NET Lecture 2
Julie Iskander
 
Session tracking In Java
Session tracking In JavaSession tracking In Java
Session tracking In Java
honeyvachharajani
 
05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07
Vivek chan
 

Similar to State management servlet (20)

Asp.net
Asp.netAsp.net
Asp.net
 
Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
 
Documentation
DocumentationDocumentation
Documentation
 
Session and state management
Session and state managementSession and state management
Session and state management
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Play framework
Play frameworkPlay framework
Play framework
 
Bt0083 server side programing
Bt0083 server side programing Bt0083 server side programing
Bt0083 server side programing
 
Student_result_management_system_project.doc
Student_result_management_system_project.docStudent_result_management_system_project.doc
Student_result_management_system_project.doc
 
State management in asp
State management in aspState management in asp
State management in asp
 
Lecture 10.pptx
Lecture 10.pptxLecture 10.pptx
Lecture 10.pptx
 
Android Trainning Session 2
Android Trainning  Session 2Android Trainning  Session 2
Android Trainning Session 2
 
GAP
GAPGAP
GAP
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - Java
 
GAP A Tool for Visualize Web Site in Heterogeneus Mobile Devices
GAP A Tool for Visualize Web Site in Heterogeneus Mobile DevicesGAP A Tool for Visualize Web Site in Heterogeneus Mobile Devices
GAP A Tool for Visualize Web Site in Heterogeneus Mobile Devices
 
J2ee servlet
J2ee servletJ2ee servlet
J2ee servlet
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3
 
ASP.NET Lecture 2
ASP.NET Lecture 2ASP.NET Lecture 2
ASP.NET Lecture 2
 
Session tracking In Java
Session tracking In JavaSession tracking In Java
Session tracking In Java
 
05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07
 

Recently uploaded

Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 

Recently uploaded (20)

Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 

State management servlet

  • 1. State management Http protocol that is used for communication between client and web server is a stateless protocol that is for each request new HTTP connection is established between client and server. The disadvantage of stateless protocol is that server fails to recognize that a series of request submitted by a user or logically related and represent a single task form end user prospective. Problem of state management deals with the maintenance of state over the stateless protocol. Following use case explains the problem of state management:
  • 2. Example 1- program ServletContext object is used for state management. Program save with Name: index.html <html> <head><title>Inter Application Forwarding..</title></head> <body> <form method="get" action="welcomeServlet"> Name :<input type="text" name="txtName"><br> <input type="submit" value="submit"> </form> </body> </html> Program save with Name: WelcomeServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String name=request.getParameter("txtName"); PrintWriter out=response.getWriter(); out.println("<b> Welcome, "+name+"</b>"); ServletConfig cnf=getServletConfig(); ServletContext ctx=cnf.getServletContext(); ctx.setAttribute("user",name); out.println("<br> <form action=tourServlet method=get>");
  • 3. out.println("<br><input type=submit value="Take a Tour "></form>" ); out.close(); } } Program save with Name: TourServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TourServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); ServletConfig cnf=getServletConfig(); ServletContext ctx=cnf.getServletContext(); String name=(String)ctx.getAttribute("user"); PrintWriter out=response.getWriter(); out.println("<b> Sorry, "+name+"</b>"); out.println("<br>Site is down for routine maintenance, vist again later.."); out.close(); } } Program save with Name: web.xml <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>welcomeServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>TourServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>tourServlet</url-pattern> </servlet-mapping> </web-app>
  • 4. Output : Run program on two browser and test with both users one by one Yes This is not complete solution of state management so there is requirement of another technique. Problem with ServletContext object when we use it for state management: Name of user is user specific which must not be store in ServletContext because other user is override it. Note: In ServletContext store only application specific data not store user specific data. Following solution is device to solve the problem of State management: 1- Cookies 2- Hidden form fields 3- URL rewriting 4- HttpSession object 1- Cookies A cookie represent information in the form of key value pair which is send by the server as part of response and is submitted by the browser to the server as part of the sub sequent request. Cookie provides a simple mechanism of maintaining user information between multiple requests. Cookie can be of 2 types: 1- Persistent cookies 2- Non Persistent cookies 1- Persistent cookies:
  • 5. Persistent cookies remain valid for multiple sessions. They are store by the browser in a text file on the client machine to be use again and again. 2- Non Persistent cookies: Non persistence cookies remain valid only for a single session, they are store in the browser cache during the session and discarded by the browser when the session is complete. Note: By default all cookies are non persistent. Advantage: 1- Simplicity is main advantage of this approach. Disadvantage: 1- This method of state maintenance is browser dependent. 2- Only textual information can be persisted between request (Object Map, File are not persisted in cookies). 3- Persistent cookies do not differentiate users on the machine. Note: Netscape first introduce cookies. javax.servlet.http.Cookie, class provides object representation of cookies. Cookies object can be created using following constructor: public Cookie(String name, String value);
  • 6. Method of Cookie class: 1- getName(): Is use to obtain the name of the cookie. public String getName(); 2- getValue(): Is use to obtain the value of the cookie. public String getValue(); 3- setMaxAge(): Is use to specify the time for which cookie remain valid. This method makes cookies persistent. public void setMaxAge(int seconds); etc… addCookie(): Method of HttpServletResponse interface is used to add the cookie as a part of the response. public void addCookie(Cookie ck); getCookies(): Method of HttpServletRequest interface is used to obtain the cookies which are submitted as part of the request. public Cookie[] getCookies(); Example 1- program for state management using Cookies. Program save with Name: index.html <html> <head><title>Inter Application Forwarding..</title></head> <body> <form method="get" action="welcomeServlet"> Name :<input type="text" name="txtName"><br> <input type="submit" value="submit"> </form> </body> </html> Program save with Name: WelcomeServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet extends HttpServlet
  • 7. { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String name=request.getParameter("txtName"); PrintWriter out=response.getWriter(); out.println("<b> Welcome, "+name+"</b>"); Cookie ck=new Cookie("user",name); response.addCookie(ck); ck.setMaxAge(60); // for making Persisted Cookies out.println("<br> <form action=tourServlet method=get>"); out.println("<br><input type=submit value="Take a Tour"></form>" ); out.close(); } } Program save with Name: TourServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TourServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String name="Gust"; Cookie ch[]=request.getCookies(); if(ch!=null) name=ch[0].getValue(); out.println("<b> Sorry, "+name+"</b>"); out.println("<br>Site is down for routine maintenance, vist again later.."); out.close(); } } Program save with Name: web.xml <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>welcomeServlet</url-pattern> </servlet-mapping>
  • 8. <servlet> <servlet-name>s2</servlet-name> <servlet-class>TourServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>tourServlet</url-pattern> </servlet-mapping> </web-app> Output : Run program on two browser and test with both users one by one Yes, now state is managed it will give correct output. 2- Hidden form field Hidden form field provide the browser independent method of maintaining state between requests. In this method information is to persistence between one request to another is contain in invisible text field which are added to the response page whenever a new request is submitted using the response page value of invisible field are posted as request parameter. Limitation: 1- Only textual information can be persisted between requests. 2- This approach can only be used when request is submitted using the form of response page that is this approach does not work with hyperlink. Example 1- program for state management using Hidden form field.
  • 9. Program save with Name: index.html <html> <head><title>Inter Application Forwarding..</title></head> <body> <form method="get" action="welcomeServlet"> Name :<input type="text" name="txtName"><br> <input type="submit" value="submit"> </form> </body> </html> Program save with Name: WelcomeServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String name=request.getParameter("txtName"); PrintWriter out=response.getWriter(); out.println("<b> Welcome, "+name+"</b>"); out.println("<br> <form action=tourServlet method=get>"); out.println("<br><input type=hidden name=txtHidden value=""+name+"">"); out.println("<br><input type=submit value="Take a Tour"></form>" ); out.close(); } } Program save with Name: TourServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TourServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String name=request.getParameter("txtHidden"); out.println("<b> Sorry, "+name+"</b>"); out.println("<br>Site is down for routine maintenance, vist again later.."); out.close(); }
  • 10. } Program save with Name: web.xml <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>welcomeServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>TourServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>tourServlet</url-pattern> </servlet-mapping> </web-app> Output : Run program on two browser and test with both users one by one Yes, now state is managed it will give correct output. 3- URL rewriting (mostly used) In this approach information to be persisted between request is dynamically appended to the URL in response page, whenever a request is submitted using these URL, append information is submitted as request parameters. Syntax of appending: URL?paramName=value & paramName=value Limitation: 1- Only textual information can be persisted using this approach. 2- In case of input form this approach work only if post request is submitted (Because get request changed the URL). Example 1- program for state management using URL rewriting (Using Form Field). Program save with Name: index.html
  • 11. <html> <head><title>Inter Application Forwarding..</title></head> <body> <form method="get" action="welcomeServlet"> Name :<input type="text" name="txtName"><br> <input type="submit" value="submit"> </form> </body> </html> Program save with Name: WelcomeServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String name=request.getParameter("txtName"); PrintWriter out=response.getWriter(); out.println("<b> Welcome, "+name+"</b>"); out.println("<br> <form method=post action="tourServlet?userName="+name+"">"); out.println("<br><input type=submit value="Take a Tour"></form>" ); out.close(); } } Program save with Name: TourServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TourServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String name=request.getParameter("userName"); if(name.equals("")) name="Gust"; out.println("<b> Sorry, "+name+"</b>"); out.println("<br>Site is down for routine maintenance, vist again later.."); out.close(); } }
  • 12. Program save with Name: web.xml <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>welcomeServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>TourServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>tourServlet</url-pattern> </servlet-mapping> </web-app> Output : In this program we are using post method for submitting request on tourServlet that help URL is overridden that is specified in program and if we using get request then new URL is created instead of specified in program. If we try to use get method then NullPointerException occure. Example 1- program for state management using URL rewriting (Using Hyperlink). Program save with Name: index.html <html> <head><title>Inter Application Forwarding..</title></head> <body> <form method="get" action="welcomeServlet"> Name :<input type="text" name="txtName"><br> <input type="submit" value="submit"> </form> </body> </html> Program save with Name: WelcomeServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*;
  • 13. public class WelcomeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String name=request.getParameter("txtName"); PrintWriter out=response.getWriter(); out.println("<b> Welcome, "+name+"</b>"); out.println("<br><a href="tourServlet?userName="+name+"">Take a Tour</a>"); out.close(); } } Program save with Name: TourServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TourServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); String name=request.getParameter("userName"); if(name.equals("")) name="Gust"; out.println("<b> Sorry, "+name+"</b>"); out.println("<br>Site is down for routine maintenance, vist again later.."); out.close(); } } Program save with Name: web.xml <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>welcomeServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name>
  • 14. <servlet-class>TourServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name> <url-pattern>tourServlet</url-pattern> </servlet-mapping> </web-app> Output : In this program use get method because Hyperlink is generate get request. 4- HttpSession javax.servlet.http.HttpSession is an interface of Servlet API. Implementation of which is provided by the vendors. An object of type HttpSession can be get created by the web server per user. This object is used by the application developer to store user information between requests. Commonly used method of HttpSession interface: 1- setAttribute(): Is used to store an attribute in the session scope. public void setAttribute(String name, Object value); 2- getAttribute(): Is used to obtain an attribute from the session scope. public Object getAttribute(String name); 3- getAttributeNames(): Is used to find out the names of attributes saved in session scope. public Enumeration getAttributeNames(); 4- removeAttribute(): Is used to remove an attributes from the session scope. public boolean removeAttribute(String name); Methods used For management Session Object: 5- isNew(): Is used to find out whether session is created for the current request or not. public boolean isNew();
  • 15. 6- setMaxInactiveInterval(): Is used to specify the time for which a session remains valid even if no request is received from the client. public void setMaxInactiveInterval(int second); 7-invalidate(): Is used to release a session. public void invalidate(); etc….. getSession(): getSession() method of HttpServletRequest interface is used to obtain a HttpSession object. public HttpSession getSession(); public HttpSession getSession(boolean createFlag); Example 1- program for state management using HttpSession object. Program save with Name: index.html <html> <head><title>Inter Application Forwarding..</title></head> <body> <form method="get" action="welcomeServlet"> Name :<input type="text" name="txtName"><br> <input type="submit" value="submit"> </form> </body> </html> Program save with Name: WelcomeServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String name=request.getParameter("txtName"); PrintWriter out=response.getWriter(); out.println("<b> Welcome, "+name+"</b>"); HttpSession session=request.getSession(); session.setAttribute("uname",name);
  • 16. session.setMaxInactiveInterval(3); // If user is ideal state max(3 second) then // Session object is destroyed. out.println("<br><a href=" tourServlet ">Take a Tour</a>"); out.close(); } } Program save with Name: TourServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class TourServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out=response.getWriter(); HttpSession session=request.getSession(); String name=(String)session.getAttribute("uname"); // session.invalidate(); // Use for destroy Session object. if(name==null) name="Guest"; out.println("<b> Sorry, "+name+"</b>"); out.println("<br>Site is down for routine maintenance, vist again later.."); out.close(); } } Program save with Name: web.xml <web-app> <servlet> <servlet-name>s1</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s1</servlet-name> <url-pattern>welcomeServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>s2</servlet-name> <servlet-class>TourServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>s2</servlet-name>
  • 17. <url-pattern>tourServlet</url-pattern> </servlet-mapping> </web-app> Output : Run program and test it frequently submitting request and wait 3 second then submit request. Yes, now state is managed it will give correct output. In order to manage session object web server create unique id for each session. Session object are store in a map by the server using the id as key. Unique identifier for each session is sent with the response in the form of cookies or request parameter using URL rewriting. When subsequent request are submitted session id is made available which is used by the server to identify the session.