SlideShare ist ein Scribd-Unternehmen logo
1 von 17
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.

Weitere Àhnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Socket programming
Socket programmingSocket programming
Socket programming
 
Caching
CachingCaching
Caching
 
Selective repeat protocol
Selective repeat protocolSelective repeat protocol
Selective repeat protocol
 
IPC (Inter-Process Communication) with Shared Memory
IPC (Inter-Process Communication) with Shared MemoryIPC (Inter-Process Communication) with Shared Memory
IPC (Inter-Process Communication) with Shared Memory
 
Get method and post method
Get method and post methodGet method and post method
Get method and post method
 
Electronic mail - Computer Networks
Electronic mail - Computer NetworksElectronic mail - Computer Networks
Electronic mail - Computer Networks
 
Chap 12 tcp
Chap 12 tcpChap 12 tcp
Chap 12 tcp
 
Distributed System - Security
Distributed System - SecurityDistributed System - Security
Distributed System - Security
 
Application layer protocols
Application layer protocolsApplication layer protocols
Application layer protocols
 
Application layer
Application layerApplication layer
Application layer
 
Hash Function
Hash FunctionHash Function
Hash Function
 
Mime
MimeMime
Mime
 
TCP/IP 3-way Handshake
TCP/IP 3-way Handshake TCP/IP 3-way Handshake
TCP/IP 3-way Handshake
 
Clock synchronization in distributed system
Clock synchronization in distributed systemClock synchronization in distributed system
Clock synchronization in distributed system
 
PHP Basic & Variables
PHP Basic & VariablesPHP Basic & Variables
PHP Basic & Variables
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
 
S/MIME
S/MIMES/MIME
S/MIME
 
Ajax ppt
Ajax pptAjax ppt
Ajax ppt
 
PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
 
Block Cipher and its Design Principles
Block Cipher and its Design PrinciplesBlock Cipher and its Design Principles
Block Cipher and its Design Principles
 

Andere mochten auch

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
 
ĐŸŃ€ĐŸŃ‚ĐŸĐșĐŸĐ» № 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 2011Ashwin 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 campaignAkash Molla
 
Deut ppt-017
Deut ppt-017Deut ppt-017
Deut ppt-017Jeff Phipps
 
Peter Opsvik's Philosophy of Sitting
Peter Opsvik's Philosophy of SittingPeter Opsvik's Philosophy of Sitting
Peter Opsvik's Philosophy of SittingErgomonkey
 

Andere mochten auch (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
 

Ähnlich wie State management servlet

Server side programming bt0083
Server side programming bt0083Server side programming bt0083
Server side programming bt0083Divyam Pateriya
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.pptJayaprasanna4
 
Documentation
DocumentationDocumentation
DocumentationKalyan A
 
Session and state management
Session and state managementSession and state management
Session and state managementPaneliya Prince
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 
Play framework
Play frameworkPlay framework
Play frameworkKeshaw 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.docAnshChhabra6
 
State management in asp
State management in aspState management in asp
State management in aspIbrahim MH
 
Lecture 10.pptx
Lecture 10.pptxLecture 10.pptx
Lecture 10.pptxJavaid Iqbal
 
Android Trainning Session 2
Android Trainning  Session 2Android Trainning  Session 2
Android Trainning Session 2Shanmugapriya D
 
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 DevicesJuan Carlos Olivares Rojas
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3sandeep54552
 
ASP.NET Lecture 2
ASP.NET Lecture 2ASP.NET Lecture 2
ASP.NET Lecture 2Julie Iskander
 
Session tracking In Java
Session tracking In JavaSession tracking In Java
Session tracking In Javahoneyvachharajani
 
05 asp.net session07
05 asp.net session0705 asp.net session07
05 asp.net session07Vivek chan
 
Ajaxppt
AjaxpptAjaxppt
AjaxpptIblesoft
 

Ähnlich wie 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
 
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
 
Ajaxppt
AjaxpptAjaxppt
Ajaxppt
 

KĂŒrzlich hochgeladen

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...gurkirankumar98700
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

KĂŒrzlich hochgeladen (20)

The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

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.