action获取原生servletAPI

来源:互联网 发布:php spark 编辑:程序博客网 时间:2024/04/29 03:23

在讲解如何获取servlet原生API之前我们有必要学习一下ActionContext,首先我们说一下其生命周期:每次请求都会创建一个与请求对应的ActionContext对象,请求处理完action自动销毁(线程安全的)。

那么让我们来看看ActionContext线程安全的实现原理吧!

static ThreadLocal<ActionContext> actionContext = new ThreadLocal<ActionContext>(); public static void setContext(ActionContext context) {        actionContext.set(context);    }    public static ActionContext getContext() {        return actionContext.get();    }


下面我们来看下面的画图讲解,将更加具体:



我想我已经介绍的很清楚了吧!我们继续,

外面看起来ActionContext是一个对象,其实它有一颗Map的心,ActionContext的核心是context对象,

 private Map<String, Object> context; public ActionContext(Map<String, Object> context) {        this.context = context;    }

然后我们看一下get()方法是如何来查找对象的:

 public Map<String, Object> getSession() {        return (Map<String, Object>) get(SESSION);    }  public Object get(String key) {        return context.get(key);    }

查找其他对象也是如下原理。但是我们是struts2所以会有不同不同于servlet的地方,struts2推荐把存放在request域中的参数放在ActionContext中,因为Struts2所返回的request对象时一个代理对象,增强了getAttribute()方法,使其在查找完reuqest域后没有找到的话,在去ActionContext中查找。

@Overridepublic String execute() throws Exception {HttpServletRequest request = ServletActionContext.getRequest();System.out.println(request);return SUCCESS;}
我们看到在控制台打印输出中看到request是一个代理对象:




原创粉丝点击