struts2的ActionContext

ActionContext是被存放在當前線程中的,獲取ActionContext也是從ThreadLocal中獲取的。因此在執行攔截器、 action和result的過程當中,因爲他們都是在一個線程中按照順序執行的,因此能夠能夠在任意時候在ThreadLocal中獲取 ActionContext。
ActionContext包括了不少信息,好比Session、Application、Request、Locale、ValueStack等,其中 ValueStack能夠解析ognl表達式,來動態後去一些值,同時能夠給表達式提供對象。值棧是創建在ognl的基礎之上的。

HttpServletRequest等對象是如何與struts2的ActionContext互通的
是struts2從新實現了HttpServletRequest接口,就是類StrutsRequestWrapper,看下struts2的說明:
All Struts requests are wrapped with this class, which provides simple JSTL accessibility. This is because JSTL works with request attributes, so this class delegates to the value stack except for a few cases where required to prevent infinite loops. Namely, we don't let any attribute name with "#" in it delegate out to the value stack, as it could potentially cause an infinite loop. For example, an infinite loop would take place if you called: request.getAttribute("#attr.foo").
說明struts從新包裝了request接口,因此若是用request.getAttribute()的話,是執行了StrutsRequestWrapper類,在這個類裏面有訪問ActionContext的代碼:
public class StrutsRequestWrapper extends HttpServletRequestWrapper {

    /**
     * The constructor
     * @param req The request
     */
    public StrutsRequestWrapper(HttpServletRequest req) {
        super(req);
    }

    /**
     * Gets the object, looking in the value stack if not found
     *
     * @param s The attribute key
     */
    public Object getAttribute(String s) {
        if (s != null && s.startsWith("javax.servlet")) {
            // don't bother with the standard javax.servlet attributes, we can short-circuit this
            // see WW-953 and the forums post linked in that issue for more info
            return super.getAttribute(s);
        }

        ActionContext ctx = ActionContext.getContext();
        Object attribute = super.getAttribute(s);
        ...java

     }app

}


在這裏實現了getAttribute方法,然而沒有實現所有,因此只有用getAttribute方法才能獲取ActionContext中的信息

可是它繼承了sun的HttpServletRequestWrapper類,因此其餘的方法仍是用的默認實現,也就是不能訪問到ActionContext中的信息

jstl標籤會觸發request等的getAttribute方法,因此jstl也能獲取到ActionContext的數據,好比Struts2的Action中的屬性等等。
 ide

相關文章
相關標籤/搜索