会话管理:session与cookie -ag凯发k8国际
1. 导言
http 是一种无状态协议,每次客户端访问web页面时,客户端打开一个单独的浏览器窗口连接到web服务器,由于服务器不会自动保存之前客户端请求的相关信息,所以无法识别一个http请求是否为第一次访问。这意味着需要有相应的技术来维持web客户端和服务器之间的会话,这就是会话跟踪。
2. cookie与session简单架构图
每一个客户端向服务器请求信息,服务器为每个客户端建立一个对话session,每个对话有一个唯一的sessionid,服务器将sessionid打包到cookie中,服务器将cookie发送给客户端。客户端保存cookie,等到下一次客户端请求服务器时,发送保存的cookie,服务器通过cookie里面的sessionid就能判别是哪一个客户端进行再次请求。
3.cookies
3.1 cookies简介
cookie 是存储在客户端计算机上的文本文件,并保留了各种跟踪信息。识别返回用户包括三个步骤:
(1)服务器脚本向浏览器发送一组 cookie;
(2)浏览器将这些信息存储在本地计算机上,以备将来使用;
(3)当下一次浏览器向web服务器发送任何请求时,浏览器会把这些cookie信息发送到服务器,服务器将使用这些信息来识别用户。
3.2 servlet中操作cookie
cookie源代码:
3.3 cookie api
cookie源代码:
// // source code recreated from a .class file by intellij idea // (powered by fernflower decompiler) //package javax.servlet.http;import java.io.serializable; import java.security.accesscontroller; import java.security.privilegedaction; import java.util.locale;public class cookie implements cloneable, serializable {private static final cookienamevalidator validation;private static final long serialversionuid = 1l;private final string name;private string value;private int version = 0;private string comment;private string domain;private int maxage = -1;private string path;private boolean secure;private boolean httponly;public cookie(string name, string value) {validation.validate(name);this.name = name;this.value = value;}public void setcomment(string purpose) {this.comment = purpose;}public string getcomment() {return this.comment;}public void setdomain(string pattern) {this.domain = pattern.tolowercase(locale.english);}public string getdomain() {return this.domain;}public void setmaxage(int expiry) {this.maxage = expiry;}public int getmaxage() {return this.maxage;}public void setpath(string uri) {this.path = uri;}public string getpath() {return this.path;}public void setsecure(boolean flag) {this.secure = flag;}public boolean getsecure() {return this.secure;}public string getname() {return this.name;}public void setvalue(string newvalue) {this.value = newvalue;}public string getvalue() {return this.value;}public int getversion() {return this.version;}public void setversion(int v) {this.version = v;}public object clone() {try {return super.clone();} catch (clonenotsupportedexception var2) {throw new runtimeexception(var2);}}public void sethttponly(boolean httponly) {this.httponly = httponly;}public boolean ishttponly() {return this.httponly;}static {boolean strictservletcompliance;string propstrictnaming;string propfwdslashisseparator;if (system.getsecuritymanager() == null) {strictservletcompliance = boolean.getboolean("org.apache.catalina.strict_servlet_compliance");propstrictnaming = system.getproperty("org.apache.tomcat.util.http.servercookie.strict_naming");propfwdslashisseparator = system.getproperty("org.apache.tomcat.util.http.servercookie.fwd_slash_is_separator");} else {strictservletcompliance = (boolean)accesscontroller.doprivileged(new privilegedaction<boolean>() {public boolean run() {return boolean.valueof(system.getproperty("org.apache.catalina.strict_servlet_compliance"));}});propstrictnaming = (string)accesscontroller.doprivileged(new privilegedaction<string>() {public string run() {return system.getproperty("org.apache.tomcat.util.http.servercookie.strict_naming");}});propfwdslashisseparator = (string)accesscontroller.doprivileged(new privilegedaction<string>() {public string run() {return system.getproperty("org.apache.tomcat.util.http.servercookie.fwd_slash_is_separator");}});}boolean strictnaming;if (propstrictnaming == null) {strictnaming = strictservletcompliance;} else {strictnaming = boolean.parseboolean(propstrictnaming);}boolean allowslash;if (propfwdslashisseparator == null) {allowslash = !strictservletcompliance;} else {allowslash = !boolean.parseboolean(propfwdslashisseparator);}if (strictnaming) {validation = new rfc2109validator(allowslash);} else {validation = new rfc6265validator();}} }3.4 简单案例
setcookie.html
<!doctype html> <html> <head><meta charset="utf-8"><title>菜鸟教程(runoob.com)</title> </head> <body> <form action="/setcookie" method="get">站点名 :<input type="text" name="name"><br />站点 url:<input type="text" name="url" /><br><input type="submit" value="提交" /> </form> </body> </html> package webstudy;import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.cookie; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; import java.io.printwriter; import java.net.urlencoder;/*** servlet implementation class helloservlet*/ @webservlet("/setcookie") public class setcookie extends httpservlet {private static final long serialversionuid = 1l;/*** @see httpservlet#httpservlet()*/public setcookie() {super();// todo auto-generated constructor stub}/*** @see httpservlet#doget(httpservletrequest request, httpservletresponse response)*/@overridepublic void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception{// 为名字和姓氏创建 cookiecookie name = new cookie("name",urlencoder.encode(request.getparameter("name"), "utf-8")); // 中文转码cookie url = new cookie("url",request.getparameter("url"));// 为两个 cookie 设置过期日期为 24 小时后name.setmaxage(60*60*24);url.setmaxage(60*60*24);// 在响应头中添加两个 cookieresponse.addcookie(name);response.addcookie(url);// 设置响应内容类型response.setcontenttype("text/html;charset=utf-8");printwriter out = response.getwriter();string title = "设置 cookie 实例";string doctype = "\n";out.println(doctype "\n" "- \n" "
- 站点名::" request.getparameter("name") "\n " "
- 站点 url::" request.getparameter("url") "\n " "
cookie 名称和值
");for (int i = 0; i < cookies.length; i){cookie = cookies[i];//比较字符串的值是否相等,-1 0 1if((cookie.getname( )).compareto("name") == 0 ){cookie.setmaxage(0);//设置过期response.addcookie(cookie);//添加cookieout.print("已删除的 cookie:" cookie.getname( ) "");}out.print("名称:" cookie.getname( ) ",");out.print("值:" urldecoder.decode(cookie.getvalue(), "utf-8") "
");}}else{out.println( "
no cookie founds
");}out.println("");out.println("");}/*** @see httpservlet#dopost(httpservletrequest request, httpservletresponse response)*/@overrideprotected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {// todo auto-generated method stubdoget(request, response);}}4. httpsession 对象
4.1 session 简介
为了让 web 应用程序能够记住用户送出的不同请求,servlet 规范内定义一个 httpsession 接口,允许 servlet 容器针对每个用户建立一个 http 会话(即 httpsession 对象),每个 http 会话将被赋予惟一的“会话编号”( session id )。
httpsession 对象会在用户第一次访问服务器时由容器创建(只有访问 jsp、servlet 等动态资源时才会创建,访问 html 等静态资源并不会创建),当用户调用其失效方法(invalidate() 方法)或超过其最大不活动(超时,timeout )时间时会失效。
servlet 容器为每个 httpsession 生成唯一的标识,并将该标识发送给浏览器,或创建一个名为 jsessionid 的 cookie ,或者在 url 后附加一个名为 jsessionid 的参数。在后续的请求中,浏览器会将标识提交给服务端,这样服务器就可以识别该请求是由哪个用户发起的。
4.2 httpsession api
httpsession 源代码:
// // source code recreated from a .class file by intellij idea // (powered by fernflower decompiler) //package javax.servlet.http;import java.util.enumeration; import javax.servlet.servletcontext;public interface httpsession {long getcreationtime();string getid();long getlastaccessedtime();servletcontext getservletcontext();void setmaxinactiveinterval(int var1);int getmaxinactiveinterval();/** @deprecated */@deprecatedhttpsessioncontext getsessioncontext();object getattribute(string var1);/** @deprecated */@deprecatedobject getvalue(string var1);enumeration<string> getattributenames();/** @deprecated */@deprecatedstring[] getvaluenames();void setattribute(string var1, object var2);/** @deprecated */@deprecatedvoid putvalue(string var1, object var2);void removeattribute(string var1);/** @deprecated */@deprecatedvoid removevalue(string var1);void invalidate();boolean isnew(); }4.3 简单案例
booklist.jsp页面显示图书购买列表,将表单数据提交给processoneservlet.java处理,processoneservlet.java将欲购买的图书数据放置在httpsession中,并请求重定向到address.jsp页面,在address.jsp页面输入客户的用户名和邮寄地址,并提交给processtwoservlet.java处理,processtwoservlet.java将客户信息和邮寄地址数据放置在httpsession中,并将请求重定向到confirmservlet.java,confirmservlet将购物信息从httpsession中取出,进行显示,实现加入购物车的功能。
booklist.jsp
<%@ page language="java" contenttype="text/html; charset=utf-8"pageencoding="utf-8"%>选择购买书籍
package book.ch4;import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import java.io.ioexception; import java.io.printwriter;@webservlet(name = "processoneservlet", urlpatterns = { "/processone" }) public class processoneservlet extends httpservlet {private static final long serialversionuid = 1l;public processoneservlet() {super();}@overrideprotected void doget(httpservletrequest request, httpservletresponse response)throws servletexception, ioexception {}@overrideprotected void dopost(httpservletrequest request, httpservletresponse response)throws servletexception, ioexception {response.setcontenttype("text/html;charset=utf-8");printwriter out = response.getwriter();httpsession session = request.getsession(true);string[] selectedbooks = request.getparametervalues("buy"); session.setattribute("choosed", selectedbooks);response.sendredirect(request.getcontextpath() "/page/ch4/address.jsp");}}address.jsp
<%@ page language="java" contenttype="text/html; charset=utf-8"pageencoding="utf-8"%>输入邮寄地址
package book.ch4;import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import java.io.ioexception; import java.io.printwriter;@webservlet(name = "processtwoservlet", urlpatterns = { "/processtwo" }) public class processtwoservlet extends httpservlet {private static final long serialversionuid = 1l;public processtwoservlet() {super();}@overrideprotected void doget(httpservletrequest request, httpservletresponse response)throws servletexception, ioexception {}@overrideprotected void dopost(httpservletrequest request, httpservletresponse response)throws servletexception, ioexception {response.setcontenttype("text/html;charset=utf-8");printwriter out = response.getwriter();httpsession session = request.getsession(true);//string customer = request.getparameter("customer");string customer = new string(request.getparameter("customer").getbytes("iso-8859-1"), "utf-8");//string address = request.getparameter("address");string address = new string(request.getparameter("address").getbytes("iso-8859-1"), "utf-8");session.setattribute("a_customer", customer);session.setattribute("a_address", address);response.sendredirect("confirm");}} package book.ch4;import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import java.io.ioexception; import java.io.printwriter;@webservlet(name = "/confirmservlet", urlpatterns = { "/confirm" }) public class confirmservlet extends httpservlet {private static final long serialversionuid = 1l;public confirmservlet() {super();}@overrideprotected void doget(httpservletrequest request, httpservletresponse response)throws servletexception, ioexception {response.setcontenttype("text/html;charset=utf-8");printwriter out = response.getwriter();httpsession session = request.getsession(true);string[] books = (string[]) session.getattribute("choosed");string customer = (string) session.getattribute("a_customer");string address = (string) session.getattribute("a_address");boolean conditon = (books != null) && (customer != null) && (address != null) && (!customer.equals("")) && (!address.equals(""));if (conditon) {system.out.println(conditon);system.out.println(!address.equals(""));system.out.println("customer=" customer);system.out.println("address=" address);out.println("");out.println("订单确认
");out.println("");out.println("");out.println("");out.println("");out.println("");out.println("");out.println("");out.println("");out.println("");out.println("");out.println("");out.println("");out.println("");out.println("顾客姓名: | " customer " |
地址: | " address " |
订购书籍: | ");for (int i = 0; i < books.length; i) {out.println(books[i] " ");}out.println(" |
无法从http会话内取出所需信息!
");out.println("");}}@overrideprotected void dopost(httpservletrequest request, httpservletresponse response)throws servletexception, ioexception {}}5. url 重写
在某些情况下,用户为了安全性可能会关闭 web 浏览器的 cookie 功能。这时候如果从用户端浏览器送出 http 请求,并不会包含 session id,因此 servlet 容器无法利用同一个 http 会话来保存不同的 http 请求内容。我们可以用url重写解决这种情况。
5.1 什么是url重写
在url重写中,我们将标记或标识符添加到下一个servlet或下一个资源的url。我们可以使用以下格式发送参数名称/值对:
url?name1=value1&name2=value2名称和值使用等号分隔,参数名称/值对与另一个参数使用&符号分隔。当用户单击超链接时,参数名称/值对将被传递到服务器。在servlet中,我们可以使用getparameter()方法获取参数值。
5.2 url重写的优势
5.3 url重写的缺点
5.4 url重写的案例
在下面的示例中,我们使用url链接维护用户的状态。为了实现此目的,我们将用户名附加在查询字符串(querystring)中,并从另一页面的查询字符串(querystring)中获取值。
url 重写通过 httpservletresponse的 encode方法和 encoderedirect方法实现,其中 encoderedirect 方法主要对使用 sendredirect () 方法的url进行重写。
5.4.1 编写页面
urlrewrite.jsp:
<%@ page contenttype="text/html;charset=utf-8" language="java" %> <html lang="en"> <head><meta charset="utf-8"><title>url重写案例title> head> <body> <form action="/servlet1">用户名:<input type="text" name="username"/><br/><input type="submit" value="提交"/> form> body> html>5.4.2 编写firstservlet
firstservlet:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;public class firstservlet extends httpservlet {private static final long serialversionuid = 1l;protected void doget(httpservletrequest request, httpservletresponse response)throws servletexception, ioexception {try{response.setcontenttype("text/html;charset=utf-8");printwriter out = response.getwriter();string n=request.getparameter("username");out.print("欢迎 "n);//把用户名追加到查询字符串后面out.print("");out.close();}catch(exception e){system.out.println(e);}} }5.4.3 编写secondservlet
secondservlet:
import javax.servlet.servletexception; import javax.servlet.http.cookie; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; import java.io.printwriter;public class secondservlet extends httpservlet {private static final long serialversionuid = 1l;protected void doget(httpservletrequest request, httpservletresponse response)throws servletexception, ioexception {try{response.setcontenttype("text/html;charset=utf-8");printwriter out = response.getwriter();//从查询字符串获取用户名string n=request.getparameter("uname");out.print("你好 "n);out.close();}catch(exception e){system.out.println(e);}} }5.4.4 配置web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"xsi:schemalocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"><servlet><servlet-name>firstservletservlet-name><servlet-class>book.ch4.firstservletservlet-class> servlet><servlet-mapping> <servlet-name>firstservletservlet-name> <url-pattern>/servlet1url-pattern> servlet-mapping><servlet> <servlet-name>secondservletservlet-name> <servlet-class>book.ch4.secondservletservlet-class> servlet><servlet-mapping> <servlet-name>secondservletservlet-name> <url-pattern>/servlet2url-pattern> servlet-mapping>web-app>
5.5 隐藏表单域
一个 web 服务器可以发送一个隐藏的 html 表单字段,以及一个唯一的 session 会话 id,如下所示:
<input type="hidden" name="session_id" value="123456789">当表单被提交时,指定的名称和值会被自动包含在表单数据中。每次当用户端浏览器发送回请求时,session_id 值可以用于保持不同的用户端浏览器的跟踪。
6. 小结
- cookie 分为会话 cookie 和持久 cookie。
会话 cookie是指在不设定它的生命周期 expires 时的状态。
浏览器的开启到关闭就是一次会话,当关闭浏览器时,会话cookie 就会跟随浏览器而销毁。
当关闭一个页面时,不影响会话 cookie 的销毁。
持久 cookie则是设定了它的生命周期 expires,关闭浏览器之后,它不会销毁,直到设定的过期时间。
对于持久 cookie,可以在同一个浏览器中传递数据,比如,你在打开一个淘宝页面登陆后,你在点开一个商品页面,依然是登录状态,即便你关闭了浏览器,再次开启浏览器,依然会是登录状态。这就是因为 cookie 自动将数据传送到服务器端,在反馈回来的结果。
-
session 是通过 cookie 技术实现的,依赖于名为 jsessionid 的 cookie,它将信息保存在服务器端。
session 中能够存储复杂的 java 对象。
session 机制是一种服务器端的机制,服务器使用一种类似于散列表的结构(也可能就是使用散列表)来保存信息。 -
由于 cookie 可以被人为的禁止,必须有其他机制以便在 cookie 被禁止时仍然能够把 session id 传递回服务器。
于是我们可以采用url 重写技术,就是把session id 直接附加在 url 路径的后面。url 重写是一种很好的维持 http 会话的方式,它在浏览器不支持 cookie 时能够很好地工作,但是它的缺点是会动态生成每个 url 来为页面分配一个 http 会话 session id。为了在整个交互过程中始终保持状态,就必须在每个客户端可能请求的路径后面都包含这个 session id。
-
隐藏表单域技术就是在表单域添加一个隐藏字段,以便在表单提交时能够把 session id 传递回服务器。
利用 form 表单的隐藏表单域,可以在完全脱离浏览器对cookie 的使用限制以及在用户无法从页面显示看到隐藏标识的情况下,将标识随请求一起传送给服务器处理,从而实现会话的跟踪。
总结
以上是ag凯发k8国际为你收集整理的会话管理:session与cookie的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: servlet入门篇(genericse
- 下一篇: 设计模式开篇