Ordinary hut

人间一福地,胜似天仙宫
posts - 61, comments - 50, trackbacks - 0, articles - 1

关于struts2的ActionContext和ValueStack的简单理解

Posted on 2009-04-07 20:47 landor 阅读(3652) 评论(0)  编辑  收藏 所属分类: struts2
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);
        

在这里实现了getAttribute方法,然而没有实现全部,所以只有用getAttribute方法才能获取ActionContext中的信息
但是它继承了sun的HttpServletRequestWrapper类,所以其他的方法还是用的默认实现,也就是不能访问到ActionContext中的信息
jstl标签会触发request等的getAttribute方法,所以jstl也能获取到ActionContext的数据,比如Struts2的Action中的属性等等。

只有注册用户登录后才能发表评论。


网站导航: