1. Struts2的ValueStack是什么:
参见李腾飞老师的讲解:http://blog.youkuaiyun.com/li_tengfei/article/details/6098134
2. Struts2的JSP为何可以通过EL表达式取得Action实例变量里的值(本质是ValueStack中的值):
参见:http://www.tuicool.com/articles/bQzaEzI
补充一点:
现在有以下情况:
public class LoginAction extends ActionSupport {
private String username;
private String password;
@Override
public String execute() throws Exception {
<span style="color:#FF0000;">setUsername("New UserName");</span>
setPassword("New Password");
<span style="color:#FF0000;">ActionContext.getContext().put("username", "Shit");</span>
}
那么JSP用EL表达式${requestScope.username}将得到什么值呢?
通过调试org.apache.struts2.dispatcher.StrutsRequestWrapper的getAttribute(String key)方法,发现它会尝试从ValueStack中取值,而且是调用com.opensymphony.xwork2.ognl.OgnlValueStack的tryFindValue(String expr)方法取的:
对Action中的username分别单独采用setUsername()和ActionContext.getContext.put()来调试,发现在com.opensymphony.xwork2.ognl.OgnlValueStack的tryFindValue(String expr)方法中,setUsername()是调用getValueUsingOgnl(expr)取值, 而ActionContext.getContext.put()是调用findInContext(expr)取值的。
至此,真相大白了。
原来,Action中的set方法是对应到ValueStack的根元素,而ActionContext.getContext.put()方法则是把值设到ValueStack的context元素中,由于context是非根元素,所以我们在JSP中用${requestScope.username}来导航对象,其实就是用先尝试从ValueStack的根对象找username,找不到再从ValueStack的context对象找。因此${requestScope.username}显示的还是“New UserName".
以下的测试再次证明上述两种设置方式在ValueStack里的区别: