SpringMVC中为什么已经作废了session, 在另一个jsp中仍然能取到session中的值?

基于用户登录注销的例子

@Controller
@SessionAttributes("loginUsername")
public class LoginController {

 private static final String LOGIN_USER = "loginUser";

 private static final String LOGIN_USERNAME = "loginUsername";
 
 @RequestMapping(value="/login", method=RequestMethod.GET)
 public String Login(Model model){
  model.addAttribute(LOGIN_USER,new User());
  return "login";
 }
 
 @RequestMapping(value="/logout", method=RequestMethod.GET)
 public String Logout(HttpSession session){
  if(null != session.getAttribute(LOGIN_USERNAME)){
   session.invalidate();
  }
  return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "login";
 }
 
 ...
}

登录成功后会在index.jsp上取session中的"loginUsername"值
  <a href=<%=request.getContextPath() + "/logout" %> >退出登录</a>
  <span><%= session.getAttribute("loginUsername")%></span>
然后"退出登录",由LoginController.Logout处理, 页面重定向到login.jsp, 以上都没问题, 但如果此时在地址栏手工输入index地址(由另一个controller处理后), 进入index.jsp, 此时发现session.getAttribute("loginUsername")仍然可以取到用户名. 断点调试确认LoginController.Logout中的session.invalidate();执行无误.可session中的对象就是不能销毁.

原因:设置了@SessionAttributes("loginUsername")
官方文档指出: The type-level @SessionAttributes annotation declares session attributes used by a specific handler. This will typically list the names of model attributes or types of model attributes which should be transparently stored in the session or some conversational storage, serving as form-backing beans between subsequent requests.
这个注解会为后面的请求保存变量在session中.
解决方法: 删除注解@SessionAttributes("loginUsername")

猜你喜欢

转载自asjava.iteye.com/blog/2253453
今日推荐