初识Struts2
Apache Struts2 是一套成熟的、基于 MVC 的 Web 应用框架。它把 WebWork 和 Struts 1.x 两套框架的长处合到了一起,用 OGNL 表达式和 Struts2 标签来读写应用数据,从而缩短按 MVC 开发 Web 应用的时间。
下面先跑通第一个程序,再对照工作原理图,把一次请求从 Filter 走到 Result 的路径看清楚。
一、Struts2 是什么
可以把它理解成:浏览器请求进来之后,由框架帮你完成「找 Action → 执行业务 → 按结果跳到 JSP / 模板」这一整套 MVC 编排。官方站点:http://struts.apache.org/。
| 你关心的事 | Struts2 怎么接 |
|---|---|
| 请求进到哪 | web.xml 里的 StrutsPrepareAndExecuteFilter |
| 业务写在哪 | 继承 ActionSupport 的 Action |
| URL 怎么对上类 | struts.xml 里的 package / action |
| 页面数据怎么取 | OGNL 表达式 + Struts2 标签 |
二、第一个 Struts2 程序
1. 下载 jar 包
到 http://struts.apache.org/ 下载 Struts2 相关 jar。
2. 最少要引入这些包
缺了会直接报错,对照下图把包加进项目:
3. 实现 Action 类
4. 核心配置 struts.xml
5. 配置 web.xml
6. 执行请求
配置好之后发请求,成功页效果如下:
三、Struts2 工作原理
一次请求在框架里大致走下面这张图(源码可看 https://github.com/apache/struts):
| 步骤 | 发生了什么 |
|---|---|
| 1 | 客户端向 Servlet 容器(如 Tomcat)发起请求 |
| 2 | 请求经过一系列 Filter;其中可选的 ActionContextCleanUp 对和其他框架(如 SiteMesh Plugin)集成很有帮助 |
| 3 | StrutsPrepareAndExecuteFilter 被调用,询问 ActionMapper:这个请求要不要进某个 Action |
| 4 | 若需要调用 Action,Filter 把处理交给 ActionProxy |
| 5 | ActionProxy 通过 Configuration Manager 读 struts.xml,找到要调用的 Action 类 |
| 6 | ActionProxy 创建 ActionInvocation 实例 |
| 7 | ActionInvocation 按命名模式调用 Action;调用前后会走相关拦截器(Interceptor) |
| 8 | Action 执行完后,按 struts.xml 找 Result:通常是 JSP 或 FreeMarker 模板(也可能是另一条 Action 链),展示时可用 Struts2 标签,过程中还会再碰到 ActionMapper |
上述过程里的 Action、Result、Interceptor 等对象,都是通过 ObjectFactory 创建的。
一句话总结:web.xml 挂上 Filter,struts.xml 把 URL 指到 Action,Action 返回 SUCCESS,框架再按 result 去渲染页面。Filter → ActionProxy → 拦截器 → Action → Result,就是 Struts2 的一条流水线。
转载请注明来源:初识Struts2










