---
title: "Struts2 的运行原理 "
author: "evenfun"
date: "2012-11-23T09:35:18Z"
tags: []
categories: ["互联网"]
slug: "struts2"
draft: false
lastmod: "2012-11-23T09:35:18Z"
id: 1733772
url: "https://sunyf.iteye.com/blog/1733772"
---

1、	运行机制
1）客户端在浏览器中输入一个url地址。
2）这个url请求通过http协议发送给tomcat。
3）tomcat根据url找到对应项目里面的web.xml文件。
4）在web.xml里面会发现有struts2的配置。
5）然后会找到struts2对应的struts.xml配置文件。
6）根据url解析struts.xml配置文件就会找到对应的class。
7）调用完class返回一个字String，根据struts.xml返回到对应的jsp。
 
2、	Struts2流程
上图来源于Struts2官方站点，是Struts 2 的整体结构。
一个请求在Struts2框架中的处理大概分为以下几个步骤：
1）客户端初始化一个指向Servlet容器（例如Tomcat）的请求。
2）这个请求经过一系列的过滤器（Filter）。
3）接着FilterDispatcher被调用，FilterDispatcher询问ActionMapper来决定这个请是否需要调用某个Action。
4）如果ActionMapper决定需要调用某个Action，FilterDispatcher把请求的处理交给ActionProxy。
5）ActionProxy通过Configuration Manager询问框架的配置文件，找到需要调用的Action类。
6）ActionProxy创建一个ActionInvocation的实例。
7）ActionInvocation实例使用命名模式来调用，在调用Action的过程前后，涉及到相关拦截器（Intercepter）的调用。
8）一旦Action执行完毕，ActionInvocation负责根据struts.xml中的配置找到对应的返回结果。
Struts2的核心就是拦截器。Struts.xml中所有的package都要extends="struts-default"。同理与所有的Java类都要extends自Object一样。struts-default.xml里面就是要做以上事情。

3、	例子
先做一个最简单的struts2的例子：在浏览器中请求一个action，然后返回一个字符串到jsp页面上显示出来。
第一步：把struts2最低配置的jar包加入的项目中。
	commons-logging-1.0.4.jar
	freemarker-2.3.8.jar
	ognl-2.6.11.jar
	struts2-core-2.0.11.jar
	xwork-2.0.4.jar
第二步：在web.xml中加入拦截器配置。

```java
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
```

第三步：把空的struts.xml配置文件放到项目src下面。

```java
	<struts>
	</struts>
```

第四部：编写自定义的action类。

```java
package test;
import com.opensymphony.xwork2.ActionSupport;
public class HelloAction extends ActionSupport {
	private String str;
	public String hello() {
		this.str = "hello!!!";
		return "success";
	}
	public String getStr() {
		return str;
	}
	public void setStr(String str) {
		this.str = str;
	}
}
```

第五步：编写struts.xml配置文件。

```java
<struts>
	<package name="test" namespace="/np" extends="struts-default">
	   <action name="hello" class="test.HelloAction" method="hello">
		   <result name="success">/hello.jsp</result>
	   </action>
	</package>
</struts>
```

第六步：编写hello.jsp文件。

```java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test</title>
</head>
<body>
	<h1><s:property value="str"/></h1>
</body>
</html>
```

第七步：启动tomcat，在浏览器中访问：
		 http://localhost:8080/hello/np/hello.action
		 hello 是项目名字
		 np 命名空间，对应namespace里面的字符串。
		 hello.action 其中hello对应action里面的字符串，“.action”表示请求的是一个action。