---
title: "struts2 in action学习笔记"
author: "rain2005"
date: "2008-11-03T12:41:39Z"
tags: []
slug: "struts2-in-action"
draft: false
lastmod: "2008-11-03T12:41:39Z"
id: 261534
url: "https://rain2005.iteye.com/blog/261534"
---

**Struts2 Action职责**

1.处理实际的业务逻辑，这一点与Struts1.x Action作用相同
2.数据转换，自动处理从request里面提取的请求参数。实际上依赖interceptor实现
3.请求转发，跳转到试图

**Struts 2 packages**
it’ll organize your actions and  other components into logical containers called packages
Struts2 package 和java包相似，都是按照功能或者业务领域把类分组。同时Struts2 package提供了继承机制。

```java
<package name="chapterThreeSecure" namespace="/chapterThree/secure"
extends="struts-default">
<action name="AdminPortfolio" >
<result>/chapterThree/AdminPortfolio.jsp</result>
</action>
<action name="AddImage" >
<result>/chapterThree/ImageAdded.jsp</result>
</action>
<action name="RemoveImage" >
<result>/chapterThree/ImageRemoved.jsp</result>
</action>
</package>
```


**ValueStack**
The Value-Stack holds a stack of objects. These objects all have properties. The magic of the  ValueStack is that all the properties of these objects appear as properties of the   ValueStack itself.
Struts Action被放在ValueStack中，所以所有Action的实例变量都是ValueStack的properties。ValueStack中的所有properties都被暴露给当前request.

**ActionContext**
ActionContext中包含session,request,application以及ValueStack中的数据。ActionContext相当于一个大的map。我们可以在页面中通过struts标签通过OGNL表达式访问ActionContext中的对象。

**OGNL**
OGNL expression必须选择一个Root Object作为访问起点，在Struts2中，ValueStack就是这个Root Object。

**再论ValueStack**
当Struts2接受一个请求时，它迅速创建ActionContext,ValueStack,action object。然后action被存到ValueStack，所以action的实例变量可以被OGNL访问。

**Interceptors**
ActionInvocation包装了Action执行的详细信息。ActionInvocation持有Action所有的拦截器引用。

```java
public String intercept(ActionInvocation invocation) throws Exception {
long startTime = System.currentTimeMillis();
String result = invocation.invoke();
long executionTime = System.currentTimeMillis() - startTime;
... log the time ...
return result;
}
```


```java
<package name="chapterFourSecure" namespace="/chapterFour/secure"
extends="struts-default">
<interceptors>
<interceptor name="authenticationInterceptor"
class="manning.utils.AuthenticationInterceptor"/>
<interceptor-stack name="secureStack">
<interceptor-ref name="authenticationInterceptor"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="secureStack"/>
. . .
</package>
```