笔者不知道该用哪个词来形容ValueStack、ActionContext等可以在Struts2中用来存放数据的类。这些类使用的范围不同,得到的方法也不同,下面就来一一介绍。
声明:本文参考Struts2版本为2.3.1.2,内容仅供参考,限于笔者水平有限,难免有所疏漏,望您能友善指出。本文发表于ITEYE,谢绝转载。
1. ValueStack
ValueStack在中文版的《Struts2深入浅出》一书中译作“值栈”。其本身数据结构是一个栈,使用者可以把一些对象(又称作bean)存入值栈中,然后使用动态的表达式来读取bean的属性,或者对bean进行一些其他操作。由于值栈中可能有多个bean,值栈会按bean出栈的顺序依次尝试使用动态的表达式来读取值,直到成功读取值为止。在Struts2中,默认的值栈实现是OgnlValueStack,即默认使用Ognl这个动态表达式语言来读取值。
在Struts2执行一次请求的过程中,Struts2会把当前的Action对象自动放入值栈。这样,在渲染JSP时,JSP里的代码使用<s:property value="..."/>之类标签中的Ognl表达式会直接作用于Action对象,从而方便的读取Action的属性。
如何得到值栈:
- 在自定义的拦截器中,使用ActionInvocation.getStack()方法( ActionInvocation 是拦截器的方法参数)。
- 在Action类中,让拦截器注入ValueStack或者使用ActionContext.getContext().getValueStack()来值栈(ActionContext.getContext()为静态方法)。注意:ActionContext分配context的方式是基于线程的,如果使用这种方法,请确保它不会出错。
- 在JSP中,直接使用标签即可获得值栈里的数据,而一般不用获取值栈本身。
如何将对象存入值栈:
- Struts2自动存入Action:之前已经提到,Struts2在执行一次请求的过程中会把当前的Action对象自动存入值栈中。
- ModelDrivenInterceptor会存入Action的model属性:如果你使用了Struts2提供的 ModelDrivenInterceptor,则它会把Action对象的getModel()方法得到的对象存入值栈中。此时,值栈最底层为Action类,其次为这个model。
- 在自定义的拦截器中存入值栈:得到值栈对象后调用ValueStack.put(Object object)方法。
- 在Action类中存入值栈:得到值栈对象后调用ValueStack.put(Object object)方法。
- 在JSP中存入值栈:标签<s:push value="..."></s:push>是专门用来在JSP中把指定的value放入值栈的,但value被放入值栈的时间仅在s:push标签内,即程序运行到</s:push>标签处会把value从值栈中移出。另外,还有一些标签比如<s:iterator/>由于其功能的需要也会把一些对象放到值栈中。
让值栈执行表达式来获得值:
- 在自定义的拦截器中,获得值栈后,使用ValueStack.findValue(...)等方法。
- 在Action类中,获得值栈后,使用ValueStack.findVlaue(...)等方法。
- 在JSP中,一些标签的属性是直接在值栈上执行Ognl表达式的,比如<s:property/>的value属性。如果标签的属性不是直接执行Ognl表达式的,则需要使用“%{}”将表达式括起来,这样Struts2就会以Ognl表达式来执行了。至于到底哪些标签是直接执行Ognl而哪些不是,请参考完整的官方文档。
在JSP中跳过栈顶元素直接访问第二层:
- 在JSP中,使用[0]、[1]等表达式来指定从栈的第几层开始执行表达式。[0]表示从栈顶开始,[1]表示从栈的第二层开始。比如表达式“name”等价于“[0].name”。参见此处。
在JSP中访问值栈对象本身(而不是它们的属性)
- 在表示式中使用top关键字来访问对象本身。比如,表达式“name”等价于“top.name”,表达式“[0].top”等价于“top”,表达式“[1].top.name”等价于“[1].name”。
总之,值栈主要目的是为了让JSP内能方便的访问Action的属性。
一些例子:
-
- public class Person {
-
- private String name;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
- }
-
- public class Person {
-
- private String name;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
- }
-
- public class MyInterceptor extends AbstractInterceptor {
-
- public String intercept(ActionInvocation invocation) throws Exception {
-
- ValueStack valueStack = invocation.getStack();
-
- Person person = new Person();
- valueStack.push(person);
-
- String name = (String) valueStack.findValue("name");
-
- return invocation.invoke();
- }
- }
-
- public class MyInterceptor extends AbstractInterceptor {
-
- public String intercept(ActionInvocation invocation) throws Exception {
-
- ValueStack valueStack = invocation.getStack();
-
- Person person = new Person();
- valueStack.push(person);
-
- String name = (String) valueStack.findValue("name");
-
- return invocation.invoke();
- }
- }
-
- public class MyAction extends ActionSupport {
-
- @Override
- public String execute() throws Exception {
-
- ValueStack valueStack = ActionContext.getContext().getValueStack();
-
- Person person = new Person();
- valueStack.push(person);
-
- String name = (String) valueStack.findValue("name");
-
-
- return SUCCESS;
- }
-
- private String message;
- private Person person;
- private List<Person> personList;
-
- public String getMessage() {
- return message;
- }
-
- public Person getPerson() {
- return person;
- }
-
- public List<Person> getPersonList() {
- return personList;
- }
- }
-
- public class MyAction extends ActionSupport {
-
- @Override
- public String execute() throws Exception {
-
- ValueStack valueStack = ActionContext.getContext().getValueStack();
-
- Person person = new Person();
- valueStack.push(person);
-
- String name = (String) valueStack.findValue("name");
-
-
- return SUCCESS;
- }
-
- private String message;
- private Person person;
- private List<Person> personList;
-
- public String getMessage() {
- return message;
- }
-
- public Person getPerson() {
- return person;
- }
-
- public List<Person> getPersonList() {
- return personList;
- }
- }
- <%@page contentType="text/html" pageEncoding="UTF-8"%>
- <%@taglib uri="/struts-tags" prefix="s" %>
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>JSP Page</title>
- </head>
- <body>
-
-
-
-
-
- <s:property value="message"/>
-
- <s:property value="getText(message)"/>
-
- <s:div cssClass="%{message}"/>
-
- <s:push value="person">
- <!-- 在此s:push标签内,值栈的栈顶元素为person,栈顶第二层为action
-
- <s:property value="name"/>
-
- <s:property value="message"/>
-
-
- <s:property value="[0].message"/>
-
- <s:property value="[1].message"/>
-
- <s:property value="top"/>
-
- <s:property value="[0].top"/>
-
- <s:property value="[1].top"/>
- </s:push>
-
-
-
- <s:iterator value="personList">
-
- <s:property value="name"/>
- </s:iterator>
- </body>
- </html>
- <%@page contentType="text/html" pageEncoding="UTF-8"%>
- <%@taglib uri="/struts-tags" prefix="s" %>
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>JSP Page</title>
- </head>
- <body>
-
-
-
-
-
- <s:property value="message"/>
-
- <s:property value="getText(message)"/>
-
- <s:div cssClass="%{message}"/>
-
- <s:push value="person">
- <!-- 在此s:push标签内,值栈的栈顶元素为person,栈顶第二层为action
-
- <s:property value="name"/>
-
- <s:property value="message"/>
-
-
- <s:property value="[0].message"/>
-
- <s:property value="[1].message"/>
-
- <s:property value="top"/>
-
- <s:property value="[0].top"/>
-
- <s:property value="[1].top"/>
- </s:push>
-
-
-
- <s:iterator value="personList">
-
- <s:property value="name"/>
- </s:iterator>
- </body>
- </html>
2.ActionContext
ActionContext是Action的上下文,Struts2自动在其中保存了一些在Action执行过程中所需的对象,比如session, parameters, locale等。Struts2会根据每个执行HTTP请求的线程来创建对应的ActionContext,即一个线程有一个唯一的ActionContext。因此,使用者可以使用静态方法ActionContext.getContext()来获取当前线程的ActionContext,也正是由于这个原因,使用者不用去操心让Action是线程安全的。
无论如何,ActionContext都是用来存放数据的。Struts2本身会在其中放入不少数据,而使用者也可以放入自己想要的数据。ActionContext本身的数据结构是映射结构,即一个Map,用key来映射value。所以使用者完全可以像使用Map一样来使用它,或者直接使用Action.getContextMap()方法来对Map进行操作。
Struts2本身在其中放入的数据有ActionInvocation、application(即ServletContext)、conversionErrors、Locale、action的name、request的参数、HTTP的Session以及值栈等。完整的列表请参考它的Javadoc(本文附录有对它包含内容的讨论)。
由于ActionContext的线程唯一和静态方法就能获得的特性,使得在非Action类中可以直接获得它,而不需要等待Action传入或注入。需要注意的是,它仅在由于request而创建的线程中有效(因为request时才创建对应的ActionContext),而在服务器启动的线程中(比如fliter的init方法)无效。由于在非Action类中访问其的方便性,ActionContext也可以用来在非Action类中向JSP传递数据(因为JSP也能很方便的访问它)。
ValueStack与ActionContext的联系和区别:
- 相同点:它们都是在一次HTTP请求的范围内使用的,即它们的生命周期都是一次请求。
- 不同点:值栈是栈的结构,ActionContext是映射(Map)的结构。
- 联系:ValueStack.getContext()方法得到的Map其实就是ActionContext的Map。查看Struts2的源代码可知(Struts2.3.1.2的org.apache.struts2.dispatcher.ng.PrepareOperations的第79行,createActionContext方法),在创建ActionContext时,就是把ValueStack.getContext()作为ActionContext的构造函数的参数。所以,ValueStack和ActionContext本质上可以互相获得。
- 注意:在一些文档中,会出现把对象存入“stack's context”的字样,其实就是把值存入了ActionContext。所以在阅读这些文档时,要看清楚,到底是放入了栈结构(即值栈),还是映射结构(值栈的context,即ActionContext)。
如何获得ActionContext:
- 在自定义的拦截器中:使用ActionInvocation.getInvocationContext()或者使用ActionContext.getContext()。
- 在Action类中:让拦截器注入或者使用ActionContext.getContext()。
- 在非Action类中:让Action类传递参数、使用注入机制注入或者使用ActionContext.getContext()。注意:只有运行在request线程中的代码才能调用ActionContext.getContext(),否则返回的是null。
- 在JSP中:一般不需要获得ActionContext本身。
如何向ActionContext中存入值:
- 在拦截器、Action类、非Action类等Java类中:使用ActionContext.put(Object key, Object value)方法。
- 在JSP中:标签<s:set value="..."/>默认将值存入ActionContext中(当然,<s:set>标签还可以把值存到其他地方)。另外,许多标签都有var属性(以前用的是id属性,现在id属性已被弃用),这个属性能向ActionContext存入值,key为var属性的值,value为标签的value属性的值。(有些文档写的是向ValueStack的context存入值,其实是一样的)
如何从ActionContext中读取值:
- 在拦截器、Action类、非Action类等Java类中:使用ActionContext.get(Object key)方法。
- 在JSP中:使用#开头的Ognl表达式,比如<s:property value="#name"/>会调用ActionContext.get("name")方法。注意:如果某标签的属性默认不作为Ognl表达式解析,则需要使用%{}把表达式括起来,于是就会出现类似“%{#name}的表达式”。(“#”的更多用途参见这里)
总之,在JSP中使用ActionContext一方面是由于它是映射结构,另一方面是能读取Action的一些配置。当你需要为许多Action提供通用的值的话,可以让每个Action都提供getXXX()方法,但更好的方法是在拦截器或JSP模板中把这些通用的值存放到ActionContext中(因为拦截器或JSP模板往往通用于多个Action)。
一些例子:
-
- public class MyInterceptor extends AbstractInterceptor {
-
- public String intercept(ActionInvocation invocation) throws Exception {
-
- ActionContext actionContext = invocation.getInvocationContext();
-
- Person person = new Person();
- actionContext.put("person", person);
-
- Object value = actionContext.get("person");
-
- HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
-
- Map requestMap = (Map) actionContext.get("request");
-
-
- return invocation.invoke();
- }
- }
-
- public class MyInterceptor extends AbstractInterceptor {
-
- public String intercept(ActionInvocation invocation) throws Exception {
-
- ActionContext actionContext = invocation.getInvocationContext();
-
- Person person = new Person();
- actionContext.put("person", person);
-
- Object value = actionContext.get("person");
-
- HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
-
- Map requestMap = (Map) actionContext.get("request");
-
-
- return invocation.invoke();
- }
- }
-
- public class MyAction extends ActionSupport {
-
- @Override
- public String execute() throws Exception {
-
- ActionContext actionContext = ActionContext.getContext();
-
- Person person = new Person();
- actionContext.put("person", person);
-
- Object object = actionContext.get("person");
-
-
- return SUCCESS;
- }
- }
-
- public class MyAction extends ActionSupport {
-
- @Override
- public String execute() throws Exception {
-
- ActionContext actionContext = ActionContext.getContext();
-
- Person person = new Person();
- actionContext.put("person", person);
-
- Object object = actionContext.get("person");
-
-
- return SUCCESS;
- }
- }
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>JSP Page</title>
- </head>
- <body>
-
-
-
-
- <s:property value="#person"/>
-
- <s:property value="#person.name"/>
-
- <s:property value="#request"/>
-
- <s:property value="#session"/>
-
- <s:property value="#parameters"/>
-
-
-
- <s:set value="%{'myName'}" var="myKey"/>
-
- <s:bean name="com.example.Person" var="myObject"/>
-
- <s:property value="#myKey"/>
- <s:property value="#myObject"/>
- </body>
- </html>
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>JSP Page</title>
- </head>
- <body>
-
-
-
-
- <s:property value="#person"/>
-
- <s:property value="#person.name"/>
-
- <s:property value="#request"/>
-
- <s:property value="#session"/>
-
- <s:property value="#parameters"/>
-
-
-
- <s:set value="%{'myName'}" var="myKey"/>
-
- <s:bean name="com.example.Person" var="myObject"/>
-
- <s:property value="#myKey"/>
- <s:property value="#myObject"/>
- </body>
- </html>
3. HttpServletRequest类或request的Map
Struts2中提供了两种对request的操作:一种是Web服务器提供的HttpServletRequest类,这和传统Java Web项目中的操作request的方式相同;另一种是一个“request的Map”,即封装了HttpServletRequest的attributes的映射类,操作该Map相当于操作HttpServletRequest的attributes。之所以提供了Map的操作方式,一是方便操作,二是能方便使用Ognl在JSP标签中读取request。无论如何,这两个request是互通的。至于request的生命周期等概念,与其他的Java Web项目没有区别,本文不再详述。
使用HttpServletRequest类还是request的Map
- 虽然两者是互通的,但就读取request的attributes而言,使用request的Map要方便许多,并且不会暴露不必要的接口。当然,HttpServletRequest有一些request的Map没有的方法,使用这些方法时当然还是要用前者。
使用request的Map还是ActionContext:
- 两者都是Map,两者的生命周期都是一个请求。
- 传统的Java Web项目中,往往是通过request的attributes来向JSP传递值的:先在Servlet里setAttribute(),然后在JSP里getAttribute()。当然在Struts2的项目中,你仍然可以使用这个方法,然而抛弃了Struts2提供的传递功能是得不偿失的。虽然笔者没有找到官方文档说一定要用ActionContext替换request的Map,也没有发现程序中有能获得ActionContext却获得不了request的Map的地方,但在Struts2框架下,操作ActionContext要比操作request的Map更加方便。因此,笔者建议:尽量使用ActionContext而不是request的Map来传递值。
- request的Map有时候会包含其他框架设置的值,比如Spring框架。获取这些值的时候就需要用request的Map了,因为ActionContext里没有。
- 通过ActionContext可以获得HttpServletRequest类:“HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);”。
- 通过ActionContext也可以获得request的Map:“Map requestMap = (Map) actionContext.get("request");”。因此,在JSP标签中,使用表达式“#request”就可以获得request的Map的数据。
如何获得HttpServletRequest:
- 如果已经有ActionContext,则使用“actionContext.get(StrutsStatics.HTTP_REQUEST)”来获得HttpServletRequest。
- 在自定义的拦截器中,先获得ActionContext,再通过ActionContext来获得。
- 在Action中,先获得ActionContext,再通过ActionContext来获得。或者让Action实现ServletRequestAware接口,并使用ServletConfigInterceptor拦截器,这样这个拦截器就会注入HttpServletRequest。
- 在JSP中,一般不需要获得HttpServletRequest。
如何获得request的Map:
- 如果已经有ActionContext,则使用“actionContext.get("request")”来获得。
- 在自定义的拦截器中,先获得 ActionContext,再通过ActionContext来获得。
- 在Action中,先获得ActionContext,再通过ActionContext来获得。或者让Action实现RequestAware接口,并使用ServletConfigInterceptor拦截器,这样这个拦截器就会注入Map request。
- 在JSP中,用“#request”来获得request的Map,用“#request.key”或者“#request['key']”来读取Map中的值。
总之,request仍然符合Java Web网站的一般规律。不过笔者建议使用者应尽量避免用request传值。
一些例子:
-
- public class MyInterceptor extends AbstractInterceptor {
-
- public String intercept(ActionInvocation invocation) throws Exception {
-
- ActionContext actionContext = invocation.getInvocationContext();
-
- HttpServletRequest httpServletRequest=(HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST);
-
- Map requestMap = (Map) actionContext.get("request");
-
- Person person = new Person();
-
- httpServletRequest.setAttribute("person", person);
- requestMap.put("person", person);
-
-
- return invocation.invoke();
- }
- }
-
- public class MyInterceptor extends AbstractInterceptor {
-
- public String intercept(ActionInvocation invocation) throws Exception {
-
- ActionContext actionContext = invocation.getInvocationContext();
-
- HttpServletRequest httpServletRequest=(HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST);
-
- Map requestMap = (Map) actionContext.get("request");
-
- Person person = new Person();
-
- httpServletRequest.setAttribute("person", person);
- requestMap.put("person", person);
-
-
- return invocation.invoke();
- }
- }
-
- public class MyAction extends ActionSupport {
-
- @Override
- public String execute() throws Exception {
-
- ActionContext actionContext = ActionContext.getContext();
-
- HttpServletRequest httpServletRequest=(HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST);
-
- Map requestMap = (Map) actionContext.get("request");
-
- Person person = new Person();
-
- httpServletRequest.setAttribute("person", person);
- requestMap.put("person", person);
-
-
- return SUCCESS;
- }
- }
-
- public class MyAction extends ActionSupport {
-
- @Override
- public String execute() throws Exception {
-
- ActionContext actionContext = ActionContext.getContext();
-
- HttpServletRequest httpServletRequest=(HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST);
-
- Map requestMap = (Map) actionContext.get("request"