Struts2 取得request session 对象
在Struts2中,从Action中取得request,session的对象进行应用是开发中的必需步骤,那么如何从Action中取得这些对象呢?
Struts2为我们提供了两种方式。
分别为:
1、servlet 相关的 非IoC 取得Request等对象的方式
这种方法可以获取servlet相关的request等对象,也就是说这种方式取出的request对象可以获取http相关的信息。
public class XXXAction extends ActionSupport{ private HttpServletRequest request; private HttpSession session; private ServletContext application; @Override public String execute() throws Exception { this.request = ServletActionContext.getRequest(); this.session = this.request.getSession(); this.application = ServletActionContext.getServletContext(); return SUCCESS; }}
public class XXXAction extends ActionSupport implements ServletRequestAware , ServletContextAware{ private HttpServletRequest request; private HttpSession session; private ServletContext application; @Override public String execute() throws Exception { this.request.setAttribute("attribute", "request value servlet 相关的 IoC "); this.session = this.request.getSession(); this.session.setAttribute("attribute", "session value servlet 相关的 IoC "); this.application.setAttribute("attribute", "application value servlet 相关的 IoC "); return SUCCESS; } @Override public void setServletRequest(HttpServletRequest request) { this.request = request; } @Override public void setServletContext(ServletContext application) { this.application = application; } }