70 likes | 145 Views
Sessions and the Web. CSE 3330 Southern Methodist University. HTTP. Client. Web server. Internet. Http is a stateless protocol . Server doesn’t know the relationship (if one even exists) between various requests made from various clients.
E N D
Sessions and the Web CSE 3330 Southern Methodist University
HTTP Client Web server Internet • Http is a stateless protocol. • Server doesn’t know the relationship (if one even exists) between various requests made from various clients. • 15 requests to the server: could be from 1 client or from 15 different clients
How can a website remember? • How can the web server remember from request to request who you are and info about your visit? • IOW: How can we track a particular user visit? • IOW: How can we maintain state between different requests from the same user? • Options: • Cookies • URL Rewriting • Session Tracking
HttpSession • In a servlet, you can get access to the current user’s session from the request object HttpSessions = req.getSession(true); • You can set key-value pairs. • keys are strings • values are Java Objects s.setAttribute(“name”, “Mark Fontenot”); true here means that If a session doesn’t already exist, create one
Accessing The Session Attributes • If you know the name of the attribute: String temp = (String)s.getAttribute(“Name”); • To iterate over all of the attributes: • Remember that attributes are stores as Objects. • Must cast to String type before storing in String var. • Note that this obviously won’t work if you store some other type in the session for (Enumeration<String> e = ses.getAttributeNames(); e.hasMoreElements(); ) { String key = e.nextElement(); Object val = ses.getAttribute(key.toString()); out.println("<br/>key = " + key + "; val = " + val.toString()); }
5 Seconds to HTML Forms <head><title>Simple Form</title></head> <body> <form name="input" action="setVals" method="get"> Key: <input type="text" name="k" /><br /> Value: <input type="text" name="v" /> <br /> <input type="submit" value="Submit" /> </form> </body> </html> When Submit Button is Clicked, will generate URL: http://localhost:8080/simpleservlet/setVals?k=name&v=mark