Struts2获得Servlet的API

1、ActionContext对象方式

(1)ActionContext对象的作用:

ActionContext对象是Struts2的一个内置对象,通过该对象可以获得Servlet的对象,如:request、response等,ActioContext对象本质上是一个Map集合。

(2)ActionContext中常见的对象

Struts2获得Servlet的API_第1张图片

 

 其中,attr域是request域、response域和application域,三个域的累计。

(3)生命周期:

每次请求都会创建一个ActionContext对象,请求处理结束该ActionContext对象销毁,其他的如:request、response的生命周期和以前一样。

(4)ActionContext对象的获取

ActionContext对象创建之后会与当前线程进行绑定,一个线程有一个唯一的ActionContext,因此,我们可以从ThreadLocal中获取ActionContext对象。

 

2、ActionContext方式:域对象值的设定与取出

(1)对每个域设定值:

public class ApiAction extends ActionSupport {
       public String execute() {
           Map requestScope= (Map) ActionContext.getContext().get("request");
           requestScope.put("name","我是用常规的方式来获得request域");

           ActionContext.getContext().put("name","我是用ActionContext的方式来获得request域");

           Map sessionScope=ActionContext.getContext().getSession();
           sessionScope.put("name","我是通过ActionContext的方式来获得的session域");

           Map applicationScope=ActionContext.getContext().getApplication();
           applicationScope.put("name","我是通过ActionContext的方式来获得的application域");
           return "success";
       }
}

其中request域的获取有两种方法,但是第一种方法较为复杂较少使用,第二种方法为获得ActionContext域,因为两个域的生命周期相同,效果也是一样的。

(2)从域中取值:


        ${requestScope.name}
${request.name}
${sessionScope.name}
${applicationScope.name}

 

 

3、ServletActionContext对象

(1)获取原生的servlet对象

      public String execute() {
           HttpServletRequest request=ServletActionContext.getRequest();

           HttpSession session=request.getSession();

           HttpServletResponse response=ServletActionContext.getResponse();

           ServletContext servletContext=ServletActionContext.getServletContext();

           return "success";
       }

(2)生命周期

ServletActionContext类直接继承了ActionContext类,两者的生命周期相同。

public class ServletActionContext extends ActionContext implements StrutsStatics {

 

4、继承接口的方式

public class ApiAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {
       private HttpServletRequest httpServletRequest;
       private HttpServletResponse httpServletResponse;
       public String execute() {
           return "success";
       }
        @Override
        public void setServletRequest(HttpServletRequest httpServletRequest) {
               this.httpServletRequest=httpServletRequest;
        }

        @Override
        public void setServletResponse(HttpServletResponse httpServletResponse) {
               this.httpServletResponse=httpServletResponse;
        }
}

即获取一个对象就要实现一个相应的接口。

 

5、总结

较为常用的是第一种方式,后两种方式都是在第一种方式之上建立的。

 

你可能感兴趣的:(Struts2获得Servlet的API)