struts2的ActionContext类分析(action执行时所需对象的环境)

来源:互联网 发布:什么是优化发展环境 编辑:程序博客网 时间:2024/04/25 07:05

        ActionContext是Action执行的一个环境。每一个ActionContext对象基本上是一个action执行所需

对象的容器,如session、parameters、locale等。(来自ActionContext API)

        ActionContext是thread local的,这意味着保存在ActionContext中的值在每个线程中都是独有的。

这样就不用担心用户具体的action context,而且自己编写的actions也是线程安全的。

public class ActionContext implements Serializable {    static ThreadLocal actionContext = new ThreadLocal();    /**     * Constant for the name of the action being executed.     */    public static final String ACTION_NAME = "com.opensymphony.xwork2.ActionContext.name";    public static final String VALUE_STACK = ValueStack.VALUE_STACK;    public static final String SESSION = "com.opensymphony.xwork2.ActionContext.session";    public static final String APPLICATION = "com.opensymphony.xwork2.ActionContext.application";    public static final String PARAMETERS = "com.opensymphony.xwork2.ActionContext.parameters";    public static final String LOCALE = "com.opensymphony.xwork2.ActionContext.locale";    public static final String TYPE_CONVERTER = "com.opensymphony.xwork2.ActionContext.typeConverter";    public static final String ACTION_INVOCATION = "com.opensymphony.xwork2.ActionContext.actionInvocation";    public static final String CONVERSION_ERRORS = "com.opensymphony.xwork2.ActionContext.conversionErrors";    public static final String CONTAINER = "com.opensymphony.xwork2.ActionContext.container";    //用于存放对应Action执行时需要的对象,可以看出使用了Map来存放,上面的常量都是Map中key    Map<String, Object> context;     /**     * Sets the action invocation (the execution state).     */    public void setActionInvocation(ActionInvocation actionInvocation) {        put(ACTION_INVOCATION, actionInvocation);    } /**     * Stores a value in the current ActionContext. The value can be looked up using the key.     */    public void put(String key, Object value) {        context.put(key, value);    }    /**     * Gets the action invocation (the execution state).     */    public ActionInvocation getActionInvocation() {        return (ActionInvocation) get(ACTION_INVOCATION);    }     /**     * Returns a value that is stored in the current ActionContext by doing a lookup using the value's key.     */    public Object get(String key) {        return context.get(key);    }     /**     * Sets the action context for the current thread.     */    public static void setContext(ActionContext context) {        actionContext.set(context);    }}

        上面的代码不是完整的,仅仅保留了ActionContext类中的成员变量定义和几个方法。成员

变量中最重要的是Map<String, Object>类型 context。从下面的get方法可以看出,context成员

变量以键值对的方式存放Action执行时所需要的对象。其他的常量成员变量表示的是Map对象

context中的键值。像action执行所需的session,application,locale,valueStack,converter等

都可以从这个类中找到。

        对应的ActionContext对象放置了一个ThreadLocal对象中,保证action执行环境是thread local

的,是线程安全的。


0 0
原创粉丝点击