Your SlideShare is downloading. ×
State management servlet
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

State management servlet

161
views

Published on

Servlets State management

Servlets State management

Published in: Technology

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
161
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 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.

×