Struts2访问servlet API的方法

来源:互联网 发布:大数据 adhoc 编辑:程序博客网 时间:2024/05/21 11:05

1、通过ActionContext类访问
ActionContext是执行时的上下文。上下文可以看作是一个容器,它存放的是Action在执行时需要用到的对象。Action运行期间所用到的数据都保存在ActionContext中。这种方式不能直接过去Servlet API实例,对于Servlet API,可以通过以下方式访问:

ActionContext context = ActionContext.getContext();context.put("name","faker");    //在request中存放context.getSession().put("name","faker");   //在session中存放context.getApplication().put("name","faker");   //在application中存放

2、通过特定的XXXAware接口访问
这种方式能够直接访问servlet API实例
有三种接口:

  • ServletContextAware:实现该接口的Action可直接访问web应用的ServletContext实例
  • ServletRequestAware:实现该接口的Action可直接访问用户请求的ServletRequestContext实例
  • ServletResponseAware:实现该接口的Action可直接访问服务器响应的ServletResponseContext实例
//先实现接口private HttpServletRequest request;在方法中request.setAttribute("name","string");

3、通过ServletActionContext类直接访问
ServletActionContext中的方法都是静态的方法,如下:

  • static PageContext getPageContext() //用于访问web应用的PageContext对象,对应JSP的内置对象page
  • static HttpServletRequest getRequest() //用于访问web应用的HttpServletRequest对象
  • static HttpServletResponse getResponse() //用于访问web应用的HttpServletResponse对象
  • static ServletContext getServletCOntext() //用于访问web应用的ServletContext对象
ServletActionContext.getRequest().setAttribute("message","Message");