您的位置:首页 > 编程语言 > Java开发

Struts框架中三种获取Session的方法

2011-06-16 17:06 274 查看
一。使用ActionContext对象

public String execute()throws Exception{
Map<String,Object> session = ActionContext.getContext().getSession();
session.put("name","tom");
return SUCCESS;
}

  

二,通过实现SessionAware接口

public class TypeAction extends ActionSupport implements SessionAware{
//继承Action可以实现验证,国际化,获取本地信息
private Map<String,Object> session;
public String execute() throws Exception{
session.put("name","tom");
return SUCCESS;
}
public String setSession(Map<String,Object> session){
this.session = session;
}
}


三,鉴于前两种获取session的方法都不是获得了真正意义的session,都不能调用session的方法

因而就有了第三种方法,仍然是采用ActionContext对象的方法,先获得HttpRequest,然后强制类型转换为其子类HttpServletRequest对象,最后再通过调用HttpServletRequest对象的方法来获取session,代码如下:

HttpSerletRequest request = (HttpServletRequest)ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
HttpSession session  = request.getSession();
//同理,HttpServletResponse 对象也是可以这样获得的
HttpSerletResponse response= (HttpServletResponse)ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);


综上,获取session对象要么通过继承帮助类(即Aware类),要么通过调用ActionContext对象的相关方法间接获得

 

其实,除了session对象,我们还可能要用到Application或Request对象,这些都是有两种获取思路,即要么使用帮助类,要么使用ActionContext对象

如Application对象可以ActionContext.getContext().getApplication()也可以像第二种获取session的方法一样继承相应的直接在Action类中声明一个Map<String,Object>类型的session并生成其set方法

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息