通俗理解encodeURL() 和 encodeRedirectURL()

来源:互联网 发布:域名怎样备案 编辑:程序博客网 时间:2024/06/06 03:15
通俗理解encodeURL() 和 encodeRedirectURL() 
我在学习过程中,难以理解response的encodeURL()和encodeRedirectURL()两个方法  
网上前辈说的大多很抽象,着实费了番功夫.所以在此分享一下个人的通俗理解,若有谬误还望指摘.  

当你所写的Servlet设置了session,你要知道当该页面被禁用cookie的用户浏览器浏览的时候,session的id(存储在响应头的cookie中)无法被该浏览器正常的带到下一个页面(通过点击链接),发送正常的包含session的id的请求头信息.  

这时候用户可以在链接地址后面加上";"+"session的id"的形式正常访问链接.你当然不可以让用户自己去做这样的事.所以response提供了这两个方法  .


response.encodeURL();
括号里填写具体的URL地址.这样当用户浏览器浏览当前servlet的时候本应包含在响应头中的session的id会以上述的";"+"session的id"形式被加入到URL后面并返回(如果没有session信息则照常返回引入的URL即可),再设置链接指向该函数返回的URL.用户点击即可在禁用cookie的情况下,带着session的id去访问该URL,发送正常的包含session的id的请求头.  

response.encodeRedirectURL():

用法与上述一致,只不过考虑特殊情况,要访问的链接可能会被Redirect到其他servlet去进行处理,这样你用上述方法带来的session的id信息不能被同时传送到其他servlet.这时候用encodeRedirectURL()方法就可以了


下面是我写的使用该方法的servlet源代码片段:

<span style="font-size:18px;">String url = response.encodeRedirectURL("/session/session2");response.getWriter().print("<a href='"+url+"'>session2</a>");</span>









下面附上javaEE的API关于这两个方法的原文说明
>  encodeURL() API原文  
> public java.lang.String encodeURL(java.lang.String url)
> Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary.





> encodeRedirectURL() API原文  
> public java.lang.String encodeRedirectURL(java.lang.String url)
> Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged. The implementation of this method includes the logic to determine whether the session ID needs to be encoded in the URL. Because the rules for making this determination can differ from those used to decide whether to encode a normal link, this method is separete from the encodeURL method.
0 0
原创粉丝点击