Struts2访问或添加request/session/application属性

在传统的Web开发中,经常会用到Servlet API中的HttpServletRequest、HttpSession和ServletContext。Struts 2框架让我们可以直接访问和设置action及模型对象的数据,这降低了对HttpServletRequest对象的使用需求,同时降低了对servletAPI的依赖性,从而降低了与servletAPI的耦合度。但在某些应用中,我们可 能会需要在action中去访问HttpServletRequest等对象,所以有时候我们不得不拉近struts2和servletAPI的关系,但struts2也有尽量减少耦合度的方法,下面我们就一起具体看一下在struts2中获得ServletAPI的方法:

 

通过ServletActionContext类直接获取:

1
2
3
4
HttpServletRequest request = ServletActionContext.getRequest();
ServletContext servletContext = ServletActionContext.getServletContext();
request.getSession();
HttpServletResponse response = ServletActionContext.getResponse();

实现指定接口,由struts框架运行时注入:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class HelloAction implements ServletRequestAware,ServletResponseAware,ServletContextAware{
  private HttpServletRequest request;
  private ServletContext servletContext;
  private HttpServletResponse response;

  public void setServletRequest(HttpServletRequest request){
    this.request = request;
  }

  public void setServletResponse(HttpServletResponse response){
    this.response = response;
  }

  public void setServletContext(ServletContext context){
    this.servletContext = context;
  }
}

添加属性:

1
2
3
4
ActionContext ctx = ActionContext().getContext();
ctx.getApplication().put("app","应用范围");   //往ServletContext里放入app
ctx.getSession().put("ses","session范围");
ctx.put("req","request范围");//往request里放入req

在JSP页面获取属性:

1
2
3
${applicationScope.app}
${sessionScope.ses}
${requestScope.req}

 

除非注明,Coder文章均为原创,转载请以链接形式标明本文地址

本文地址:http://www.alonemonkey.com/aplreqresp.html

本文链接:http://www.alonemonkey.com/aplreqresp.html