天天看點

Spring MVC中jsessionid所引起的問題 和解決



轉自:http://blog.csdn.net/seakingwy/article/details/1933687

jsessionid所引起的問題

在spring mvc當使用redirectview或者"redirect:"字首來做重定向時,spring mvc最後會調用:

response.sendredirect(response.encoderedirecturl(url));

這是典型的java做事的方式,其他語言的伺服器端平台并不會這樣做。這個jsessionid很多時候會引起嚴重的問題,例如,如果你使用上述帶有jsessionid的url直接通路新浪的網站,ie會向你報告:找不到伺服器。

解決方法:

1. 不通過spring mvc做重定向,自己直接調用:

response.sendredirect(url);

return null; //告訴spring mvc我已經完成了處理

2. 修改spring mvc的代碼,将:

改為:

3. encoderedirecturl()僅在無法确定浏覽器是否支援cookie的時候才會在url後面附加上jsessionid,如果它能找到一個jsessionid的cookie,它就認為浏覽器是支援cookie的。是以可以自己建立一個jsessionid的cookie來欺騙encoderedirecturl()。

cookie cookie = new cookie("jsessionid", "2jcligmgi6fh");

cookie.setmaxage(integer.max_value);

response.addcookie(cookie);

然後再調用spring mvc的重定向功能就沒有問題了:

return new modelandview("redirect:"+url);

無疑,這裡最好的方法是第3種方法。

轉向相同的域,因為之前伺服器已經設定了jsessionid這個cookie,并且可以得到這個cookie,是以就不必像上面第一次那樣采用url重寫的方式,url後面不會附加上jsessionid。是以當你的應用隻會轉向相同的域時,直接使用spring mvc的重定向(實際上是最後使用encoderedirecturl())不會有任何問題。

相關資料:

spring mvc redirectview appends jsessionid:

<a target="_blank" href="http://robobruin.blogspot.com/2005/12/spring-mvc-redirectview-appends.html">http://robobruin.blogspot.com/2005/12/spring-mvc-redirectview-appends.html</a>

jsessionid considered harmful:

<a target="_blank" href="http://randomcoder.com/articles/jsessionid-considered-harmful">http://randomcoder.com/articles/jsessionid-considered-harmful</a>

cookie和會話狀态的工作原理及cookie欺騙|cookie,會話狀态,cookie欺騙:

<a target="_blank" href="http://www.yuanma.org/data/2006/0908/article_1489.htm">http://www.yuanma.org/data/2006/0908/article_1489.htm</a>