【Struts2】Struts2获取session的三种方式

1、Map<String,Object> map =  ActionContext.getContext().getSession();

2、HttpSession session = ServletActionContext.getRequest().getSession();

3、让Action实现SessionAware接口,并实现public void setSession(Map<String, Object> session) {} 方法,Struts2会在实例化Action后调用该方法,通过方法参数将Session对象注入进来。如果我们想获取Session,我们可以定义成员变量,接收注入进来的Session对象。

比如:

public class UserAction implements SessionAware{    
      private Map<String,Object> session;

      //.........     
    
    @Override
    public void setSession(Map<String, Object> session) {
        this.session=session;
        
    }
}


三种方式的比较:

返回类型的对比:1,3获取的Session类型是Map<String,Object>类型,2获取的类型是HttpSession。

获取方式对比:

1,2是我们主动获取Session,3是采用注入的方式自动注入Session,这是被动的。

推荐使用3来创建Session,因为它更为灵活而且符合面向接口编程的思想。

上面的第三种方式介绍了Action使用实现SessionAware的方式获得封装了session的Map对象,除此之外还有提供如下的接口RequestAware(获得封装了request的Map对象),ApplicationAware(获得封装了application的session对象),ServletRequestAware(获得HttpServletRequest对象),ServletResponseAware(获得HttpServletResponse对象),ServletContextAware(获得ServletContext对象)。

原文链接:Struts2中获取session的三种方式

原文地址:https://www.cnblogs.com/HDK2016/p/7309268.html