最近用Wicket框架,要用到session,而Wicket中定义的session与以前常说的session(HttpSession)是不一样。
获取 httpServletSession
第二种,Wicket中提供了一个WebSession类,我们只需要继承WebSession,就可以写我们自己的Session类
具体解释摘录《Wicket开发指南》:
Wicket中的Session是指每一个Application中所拥有的数据,离开这个Application,如转向一个网站内部html,或者另一个Application,相应的Session就会无效。
而HttpSession完全不同,它保存的是用户在访问一个网站期间的会话信息。
OK,在Wicket开发时,我们也会用到HttpSession进行会话管理,网上找了一些前辈的资料,再加上自己总结了一下。
有两种方式可以实现:
第一种,使用httpServletSession:
设置httpServletSession:
HttpServletRequest request=getWebRequestCycle().getWebRequest().getHttpServletRequest();
request.getSession().setAttribute("username", username);
获取 httpServletSession
HttpServletRequest request=getWebRequestCycle().getWebRequest().getHttpServletRequest();
String userLoginName = (String) request.getSession().getAttribute("username");
第二种,Wicket中提供了一个WebSession类,我们只需要继承WebSession,就可以写我们自己的Session类
MySession类:
public class MySession extends WebSession{
private String username;
private String department;
private String rolename;
private int userid;
public MySession(Request request){
super(request);
}
/*
* 获得session
*/
public MySession session(){
return (MySession)Session.get();
}
/*
* 销毁session
*/
public void sessionInvalidate(){
this.session().invalidate();
}
public String getUsername () {
return userid;
}
public void setUserid(String username) {
this.username = username;
}
public MySession newSession(Request request, Response response) {
return new MySession(request);
}
Application就自动给MySession添上Request对象。
注意,Wicket的Session是由Wicket的Application绑定的,因此MySession只会存活在这个WebApplication里面。
最后,调用Session:设置session:
MySession mySession = (MySession) super.getSession();
mySession.session().setUsername(username);
获取session:
MySession mySession = (MySession) super.getSession();
String department = mySession.session().getDepartment();
销毁session:
MySession mySession = (MySession) super.getSession();
mySession.session().sessionInvalidate();
完成!
第二种方案是比较好的,Wicket自身的WebSession中,就使用了HttpSession,直接调用方法就行!