客户端cookie不可用时,解决方案

String encodeURL(String url) 
          Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. 


在客户端禁用了cookie后,如果不用这个方法来ecnode一下URL,那么session就无法使用。 
加了此方法后会在url后面追加jsession=*******的信息,也就是追加session ID。

jsession:会话cookie的名字

O_Reilly书籍对此问题的建意

I recommend that you take the time to add encodeURL( ) calls for all references up front, even if you know
that all your current users have browsers that support cookies. One day you may want to extend the user
base and lose control over the browsers they use. It's also common that users disable cookies in fear of Big
Brother watching. Yet another reason to prepare for URL rewriting from the beginning is to support new types
of clients that are becoming more and more common, such as PDAs and cell phones. Cookie support in these
small devices is not a given.

知识点扩展:

在Tomcat 6.0.16.中,Session的创建是调用org.apache.catalina.connector.Request类中的doGetSession()方法来完成的。下面我们给出这个方法的代码片段:

Java代码

1.protected Session doGetSession(boolean create) 
2.{
3.    …
4.    // Creating a new session cookie based on that session
5.    if ((session != null) && (getContext() != null)
6.           && getContext().getCookies()) 
7.    {
8.        Cookie cookie = new Cookie(Globals.SESSION_COOKIE_NAME,
9.                                           session.getIdInternal());
10.        configureSessionCookie(cookie);
11.        response.addCookieInternal(cookie);
12.    }
13.
14.    if (session != null) 
15.    {
16.        session.access();
17.        return (session);
18.    }
19.    else
20.    {
21.        return (null);
22.    }
23.}
24.
25.protected void configureSessionCookie(Cookie cookie) 
26.{
27.    cookie.setMaxAge(-1);
28.    String contextPath = null;
29.    if (!connector.getEmptySessionPath() && (getContext() != null)) 
30.    {
31.        contextPath = getContext().getEncodedPath();
32.    }
33.    if ((contextPath != null) && (contextPath.length() > 0)) 
34.    {
35.        cookie.setPath(contextPath);
36.    }
37.    else 
38.    {
39.        cookie.setPath("/");
40.    }
41.    if (isSecure()) 
42.    {
43.        cookie.setSecure(true);
44.    }
45.}

 

代码的第8行,我们看到非常熟悉的创建Cookie对象的代码,Cookie的名字是Globals.SESSION_ COOKIE_NAME,SESSION_COOKIE_NAME被定义为静态的常量,其值为JSESSIONID。Cookie的值是调用session.getIdInternal ()得到的Session ID。第10行,调用了configureSessionCookie()方法来配置会话Cookie。我们转到configureSessionCookie()方法中,第27行,调用Cookie对象的setMaxAge()方法设置Cookie的生存时间,在“使用Cookie的实例”的例子中,我们说过, 如果时间值为负数,那么当客户端的浏览器退出,Cookie将会被删除。看到这儿,我们就知道了为什么会话Cookie只能保存在内存中了,这是由Tomcat的实现决定的。第35行,调用Cookie对象的setPath()方法,指定这个Cookie在当前Web应用程序的上下文路径下有效。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值