Springsecurity常见错误
# jsessionid引发的问题
在Spring MVC当使用RedirectView或者"redirect:"前缀来做重定向时,Spring MVC最后会调用:
response.sendRedirect(response.encodeRedirectURL(url));
对于IE来说,打开一个新的浏览器窗口,第一次访问服务器时,encodeRedirectURL()会在url后面附加上一段jsessionid,如果初始的url为"http://www.sina.com.cn (opens new window)",最终得到的url为"http://www.sina.com.cn;jsessionid=2jcligmgi6fh (opens new window)"。
这是典型的Java做事的方式,其他语言的服务器端平台并不会这样做。这个jsessionid很多时候会引起严重的问题,例如,如果你使用上述带有jsessionid的url直接访问新浪的网站,IE会向你报告:找不到服务器。
解决方法: 1、不通过Spring MVC做重定向,自己直接调用: response.sendRedirect(url); return null; //告诉Spring MVC我已经完成了处理
2、修改Spring MVC的代码,将: response.sendRedirect(response.encodeRedirectURL(url)); 改为:response.sendRedirect(url);
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);
2
3
然后再调用Spring MVC的重定向功能就没有问题了: return new ModelAndView("redirect:"+url);
无疑,这里最好的方法是第3种方法。
转向相同的域,因为之前服务器已经设置了jsessionid这个cookie,并且可以得到这个cookie,因此就不必像上面第一次那样采用url重写的方式,url后面不会附加上jsessionid。因此当你的应用只会转向相同的域时,直接使用Spring MVC的重定向(实际上是最后使用encodeRedirectURL())不会有任何问题。
# 让请求支持; 矩阵变量
//1、WebMvcConfigurer定制化SpringMVC的功能
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
/**
* 启用矩阵变量功能 @GetMapping("/boss/{bossId}/{empId}") /boss/1;age=20/2;age=10
*/
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
// 不移除;后面的内容。矩阵变量功能就可以生效
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
};
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
参考文章:
手把手教你干掉 SpringBoot 项目地址栏中 URL 后面的 jsessionid – 业余草 (xttblog.com) (opens new window)