关于session

以前用session时只知道session是和服务器连接的一个会话,有几个常用的接口。
这两天仔细看了下这方面的资料,在这里和大家一起分享,如果有写的不正确的地方,请指正,谢谢。
下面我们在一个servlet中写测试程序,class名为SeesinInfoServlet,我们一般在程序中取得session是用
request的getSession()来取得容器中的session,该方法当容器中已经存在了该session的时候,返回已经存
在的session,否则创建一个新的session,然后返回创建的session。request还有另外一个getSession()的重
载方法:HttpSession getSession(boolean create),一般不常用,大家可以查j2ee的api,每个session都对应
唯一的sessionId,sessionId可以通过getId()方法获得,session是维持客服端和服务器端状态的一个东西,是
通过sessionId来一一对应的,客服端的sessionId一般保存在cookie中,如果客服端的cookie没有被禁掉的话
。如果cookie被禁掉,我们可以通过URL重写来实现把sessionId传到服务器。请看下面程序。
import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class SeesinInfoServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter pw = res.getWriter(); HttpSession s = req.getSession(); pw.write("New Session:" + s.isNew() + "<br>"); pw.write("Session Id:" + s.getId() + "<br>"); pw.write("Session Create Time:" + new Date(s.getCreationTime()) + "<br>"); pw.write("<br>"); pw.println("<h3>Request Information</h3>"); pw.println("Session Id from Request:" + req.getRequestedSessionId()+ "<br>"); pw.println("Session Id via Cookie:" + req.isRequestedSessionIdFromCookie()+ "<br>"); pw.println("Session Id rewritten Url:" + req.isRequestedSessionIdFromURL()+ "<br>"); pw.println("valid session id:" + req.isRequestedSessionIdValid()+ "<br>"); //pw.println("<a href="+ res.encodeURL(" mce_href="+ res.encodeURL("SessionInfoServlet")+">refresh</a>"); pw.println("<a href="SessionInfoServlet" mce_href="SessionInfoServlet">refresh</a>"); pw.close(); } }

PrintWriter pw = res.getWriter();这一句取得服务器端反映给客服端的输出流。
HttpSession s = req.getSession();取得session。
req.getRequestedSessionId();这一句取得客服端cookie中的sessionId,如果cookie没有被禁掉的话,第一次访问为null,因为还没创建session,以后每次都和
s.getId() 取得的值一致。
req.isRequestedSessionIdFromCookie();如果没有禁掉cookie,返回true。
req.isRequestedSessionIdFromURL();是否通过URL重写取得sessionId,
//pw.println("<a href="+ res.encodeURL("SessionInfoServlet")+">refresh</a>");其中的res.encodeURL(String),即为URL重写,我们可以看到地址栏后会跟sessionId。
如果不是URL重写,则地址栏中没有sessionId。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值