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

来源:互联网 发布:淘宝 装修市场 编辑:程序博客网 时间:2024/05/18 04:01

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 session5.    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.    else20.    {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应用程序的上下文路径下有效。

原创粉丝点击