打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Response 对象encodeURL 与encodeRedirectURL

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.
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.
从API可以看出不管是encodeURL还是encodeRedirectURL都要判断是否需要添加sessionid  例如 String str=response.encodeURL("index.jsp"); 变量str保存的值为
index.jsp;jsessionid=A9B0F04345178E7BDC3626EAF666D34C 如果没有禁用Cookie,刷新浏览器str为index.jsp.

出现以上情况是因为session 与cookie 成对使用的.第一次访问页面时cookie中sessionid没有值(或者值为空)故encodeURL认为需要添加jsessionid需要传递session对象,重写了URL但是在没有禁用cookie浏览器中第一访问页面时cookies对象会保存sessionid 故再次刷新不再需要重写URL.

 

session对象能和客户建立意义对应的关系依赖于客户的浏览器是否支持cookie,如果客户的浏览器不支持的话,那么客户再不同网页之间的session对象可能时互不相同的,因为服务器无法将ID存放到客户端,就不能建立session对象和客户的一一对应关系。可以通过URL重写来实现session对象的唯一性。所谓URL重写就是当客户从一个页面重新连接到一个页面时,通过向这个新的URL添加参数,把session对象的id传过去,这样能够保证session对象是完全相同的。可以使用response对象调用encodeURL()或encodeRedirectURL()方法实现URL重写。

eg:

String str=response.encodeURL("hope.jsp");  //使用在jsp页面中。

连接目标写成:<%=str%>即可。

encodeURL()是本应用级别的,encodeRedirectURL()是跨应用的。  

 两者的区别:

在使用重定向时,response.sendRedirect(response.encodeRedirectURL(***));时一定要使用encodeRedirectUrl();

由于附加在URL中的session ID是动态产生的,对每一个用户是不同的,所以对于静态页面的相互跳转,URL重写机制无能为力。当然可以通过将静态页面转换为动态页面解决。


方法的执行:首先判断当前的Servlet是否执行了HttpSession对象的invalidate()方法(当前session是否失效,失效后重新建立新的session),如果已经执行返回参数URL。接下来判断客户端是否禁用了Cookie,没有禁用直接返回参数URL,如果禁用,则在参数URL中附加session ID,返回编码后的URL。


 

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
会话技术之 Session
http session 基础知识(转)
Cookie和Session专题
response.encodeURL的用法 - 神雕大侠 - JavaEye技术网站
Web项目答辩问题
session
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服