Struts2与Ognl (转载)

一.struts2的context对象

1.下面的脚本能打印出context的内容(也可通过<s:debug>来查阅)

<%@page language="java" contentType="text/html;charset=GBK" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
  </head>
  <body>
    <s:set name="v1" value="'0123456789'"/>
<%
  Map ctx =((ValueStack)request.getAttribute("struts.valueStack")).getContext();
  Set keys = ctx.keySet();

  for (Object key:keys) {
    out.println("key=" + key + ",");
    if (ctx.get(key) != null) {
      out.println("value=" + ctx.get(key));
    }
    out.println("<br/>");
  }
%>
  </body>
</html>

上面设置了一个字符串变量v1,值是'01234567890'.

2.结果:

key=com.opensymphony.xwork2.ActionContext.parameters,value={}

key=last.bean.accessed,

key=parameters,value={}

key=com.opensymphony.xwork2.ActionContext.locale,value=zh_CN

key=current.property.path,

key=session,value={}

key=attr,value=org.apache.struts2.util.AttributeMap@c8570c

key=com.opensymphony.xwork2.util.ValueStack.ValueStack,value=com.opensymphony.xwork2.util.OgnlValueStack@caf0ed

key=com.opensymphony.xwork2.ActionContext.application,value={org.apache.catalina.jsp_classpath=...,...}

key=v1,value=0123456789

key=__component_stack,value=[]

key=com.opensymphony.xwork2.dispatcher.HttpServletRequest,value=org.apache.struts2.dispatcher.StrutsRequestWrapper@717d91

key=com.opensymphony.xwork2.dispatcher.ServletContext,value=org.apache.catalina.core.ApplicationContextFacade@eafb71

key=last.property.accessed,

key=com.opensymphony.xwork2.dispatcher.PageContext,value=org.apache.jasper.runtime.PageContextImpl@121df2a

key=com.opensymphony.xwork2.dispatcher.HttpServletResponse,value=org.apache.catalina.connector.ResponseFacade@c26b16

key=request,value={struts.valueStack=com.opensymphony.xwork2.util.OgnlValueStack@caf0ed}

key=com.opensymphony.xwork2.ActionContext.session,value={}

key=application,value={org.apache.catalina.jsp_classpath=...,...}

二.struts2的root对象

是OgnlValueStack实例,实现了ValueStack接口.

OgnlValueStack实例包含了一个ArrayList容器,提供了push和pop方法来装载对象.

当要我们通过Ognl获取一个属性时,例如<s:propertyvalue="age">,因为不带#号,说明是root对象属性,Struts对逐一顺次查找ArrayList容器中的对象,看它们是否拥有age属性,或者是有key="age"的Map.

1.com.opensymphony.xwork2.util.CompoundRootAccessor的getProperty方法源码:

public Object getProperty(Map context, Object target, Object name) throws OgnlException {
 CompoundRoot root = (CompoundRoot) target;
 OgnlContext ognlContext = (OgnlContext) context;

 if (name instanceof Integer) {
   Integer index = (Integer) name;
   return root.cutStack(index.intValue());
 } else if (name instanceof String) {
   if ("top".equals(name)) {
     if (root.size() > 0) {
       return root.get(0);
     } else {
       return null;
     }
   }

   for (Iterator iterator = root.iterator(); iterator.hasNext();) {
     Object o = iterator.next();

     if (o == null) {
       continue;
     }

     try {
       if ((OgnlRuntime.hasGetProperty(ognlContext, o, name)) || ((o instanceof Map) && ((Map) o).containsKey(name)))
       {
         return OgnlRuntime.getProperty(ognlContext, o, name);
       }
     } catch (OgnlException e) {
       if (e.getReason() != null) {
         final String msg = "Caught an Ognl exception while getting property " + name;
         throw new XWorkException(msg, e);
       }
     } catch (IntrospectionException e) {
       // this is OK if this happens, we'll just keep trying the next
     }
   }

   return null;
 } else {
   return null;
 }
}

2.查看ValueStack内容(也可通过<s:debug>来查阅):

<%@page language="java" contentType="text/html;charset=GBK" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
  </head>
  <body>
    <s:push value="'01234567890'">
    <%
      ValueStack vs = (ValueStack)request.getAttribute("struts.valueStack");
      int objCount = vs.size();
      List<Object> l = new ArrayList<Object>();
      while(--objCount >= 0) {
        Object o = vs.pop();
        l.add(o);
        if (o != null) {
          out.println("class:" + o.getClass().getName() + ":" + o + "<br/>");
        } else {
          break;
        }
      }
      
      for (int i = l.size() - 1; i >= 0; i--) {
        Object o = l.get(i);
        vs.push(o);
      }
    %>
    </s:push>
  </body>
</html>

3.结果

class:java.lang.String:01234567890

class:com.opensymphony.xwork2.DefaultTextProvider:com.opensymphony.xwork2.DefaultTextProvider@6f8b2b

三.访问

1.访问context中的变量

<%@page import="com.opensymphony.xwork2.util.ValueStack,test.model.*,java.util.*" %>
<%@page language="java" contentType="text/html;charset=GBK" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
  </head>
  <body>
    <jsp:useBean id="user0" class="test.model.User" scope="request"/>
    <jsp:setProperty name="user0" property="name" value="LiSi"/>
    <jsp:setProperty name="user0" property="id" value="0001"/>
    
    <s:set name="user1" value="#request['user0']"/>
    #user1.name:<s:property value="#user1.name"/><br/>
    #user1.id:<s:property value="#user1.id"/><br/>
  </body>]</html>

语法是<s:propertyvalue="#变量名.属性名"/>

2.访问root中的变量属性

<%@page import="com.opensymphony.xwork2.util.ValueStack,holly.model.*,java.util.*" %>
<%@page language="java" contentType="text/html;charset=GBK" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
  <head>
  </head>
  <body>
    <jsp:useBean id="user0" class="holly.model.User" scope="request"/>
    <jsp:setProperty name="user0" property="name" value="LiSi"/>
    <jsp:setProperty name="user0" property="id" value="0001"/>
    
    <s:push value="#request['user0']">
      name:<s:property value="name"/><br/>
      id:<s:property value="id"/><br/>
    </s:push>
  </body>
</html>

语法是<s:propertyvalue="属性名"/>,也可以是<s:propertyvalue="[index_number].属性名"/>index_number是元素在ArrayList容器中的位置,从0计起

四.<s:set>

1.属性

name:生成的新变量的名称

value:将赋给变量的值,如果没有指定,则将ValueStack栈顶的值赋予它.

scope:变量放置的范围.接受application,session,request,page,action五个值.不指定时,将默认放在page和context对象中.

2.例子

<s:set value="'012345678'" name="v1" scope="session"/>
<s:property value="#session.v1"/><!--等同于#session['v1']-->
<s:property value="#attr.v1"/><!--等同于#attr['v1']-->
<s:set value="'01234567890'" name="v2"/>
<s:property value="#v2"/>
<s:property value="#attr.v2"/>

v1放在了session容器中,session容器又是context对象中的一员,所以可以通过#session.v1访问.而v2因为没有指定scope,会同时放在context和page(可通过attr引用到,attr会依次在page,request,session,application中查找)中.

五.<s:push>

开始时将值推入ValueStack栈顶,结束后将值推出栈.

value属性:需要放到ValueStack栈顶的值

六.疑惑与解惑

1.疑惑

在<<Struts2权威指南>>第10.3.2iterator标签小节,看到下面这个例子:

<table border="1" width="100"
<s:iterator value="{'Spring2.0宝典','轻量级J2EE企业应用实践','基于J2EE的Ajax宝典'}" id="name">
  <tr>
    <td><s:property value="name"/></td>
  </tr>
</s:iterator>
</table>

<s:iterator>的当前值会放入两个地方,一是ValueStack栈顶,二是context容器中.引用的方法也相应有两种:

<s:property/>和<s:propertyvalue="#name"/>.

<s:propertyvalue="name"/>为什么也生效了?它找的是ArrayList容器中某个对象的name属性或'name'键对应的值.ValueStack中并没有这样的对象啊.

2.解惑

从com.opensymphony.xwork2.util.OgnlValueStack中找到了答案.

public Object findValue(String expr) {
 try {
  if (expr == null) {
   return null;
  }

  if ((overrides != null) && overrides.containsKey(expr)) {
   expr = (String) overrides.get(expr);
  }

  if (defaultType != null) {
   return findValue(expr, defaultType);
  }

  Object value = OgnlUtil.getValue(expr, context, root);
  if (value != null) {
   return value;
  } else {
   return findInContext(expr);//程序会运行到此
  }
 } catch (OgnlException e) {
  return findInContext(expr);
 } catch (Exception e) {
  logLookupFailure(expr, e);

  return findInContext(expr);
 } finally {
  OgnlContextState.clear(context);
 }
}

private Object findInContext(String name) {
  return getContext().get(name);
}

当ValueStack的ArrayList容器中以及Ognl表达式求解都不能获取到对象时,ValueStack直接从context对象中获取对象.而#name之前已经以"name='书名'"存于context中,所以会有值返回.

注意:<s:iterator>结束后,并未清除context中的name变量

3.进一步

是不是其它context中的对象都可以不通过#来访问呢?

<s:propertyvalue="session"/>行不行呢?

答案是不行,会抛出下面的异常:

java.lang.ClassCastException:org.apache.struts2.dispatcher.SessionMap

org.apache.struts2.components.Property.start(Property.java:136)

org.apache.struts2.views.jsp.ComponentTagSupport.doStartTag(ComponentTagSupport.java:54)

看org.apache.struts2.components.Property源码

public boolean start(Writer writer) {
 boolean result = super.start(writer);

 String actualValue = null;

 if (value == null) {
  value = "top";
 }
 else if (altSyntax()) {
  // the same logic as with findValue(String)
  // if value start with %{ and end with }, just cut it off!
  if (value.startsWith("%{") && value.endsWith("}")) {
   value = value.substring(2, value.length() - 1);
  }
 }

 // exception: don't call findString(), since we don't want the
 //   expression parsed in this one case. it really
 //   doesn't make sense, in fact.
 actualValue = (String) getStack().findValue(value, String.class);//这是出错的地方

 try {
  if (actualValue != null) {
   writer.write(prepare(actualValue));
  } else if (defaultValue != null) {
   writer.write(prepare(defaultValue));
  }
 } catch (IOException e) {
  LOG.info("Could not print out value '" + value + "'", e);
 }

 return result;
}

getStack().findValue(value,String.class)返回的是org.apache.struts2.dispatcher.SessionMap对象,不能被cast成String.而我们之前的变量name本身就是String,所以不会出错.

4.结论

context中的String变量可以不加#来访问.

<s:set name="v1" value="'123'"/>
<s:property value="v1"/>
<s:property value="#v1"/>
为了规范起见, 还是应该加#访问

解析源码是我们学习的最好途径

相关推荐