欢迎浏览 Java 工程师 SSH 教程从零打造在线网盘系统系列教程, 本系列教程将会使用 SSH(Struts2+Spring+Hibernate)打造一个在线网盘系统, 本系列教程是从零开始, 所以会详细以及着重地阐述 SSH 三个框架的基础知识, 第四部分将会进入项目实战, 如果您已经对 SSH 框架有所掌握, 那么可以直接浏览第四章, 源码均提供在 GitHub/SSH-network-hard-disk 上供大家参阅
本篇目标
掌握 Struts2 工作流程
掌握 Struts2 控制器
掌握 Struts2XML 配置
掌握 Struts2 注解配置
了解 Struts2 的浏览器插件
Struts2 概述
Struts2 是一个基于 MVC 设计模式的 web 应用框架, 它本质上相当于一个 servlet, 在 MVC 设计模式中, Strus2 作为控制器 (Controller) 来建立模型与视图的数据交互. Struts2 使用了大量的拦截器来处理用户请求, 从而将业务逻辑控制器和 ServletAPI 分离
Struts2 工作流程
客户端发起请求
核心控制器 FilterDispatcher 拦截请求调用 Action
调用 Action 的 execute 方法前调用一系列的拦截器
调用 execute 执行业务逻辑
返回结果
控制器是 What?
包含 execute 方法的 POJO 既可以作为控制器, 即一个简单的 JAVA 类包含一个 execute()方法就可以作为控制器, 同时控制器具有封装客户端请求参数的能力.
- public class TestAction {
- public String execute() throws Exception {
- return "test";
- }
- }
Struts2XML 配置
xml 配置完整工程示例源码下载
导入 struts 依赖 jar
- <!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-core -->
- <dependency>
- <groupId>org.apache.struts</groupId>
- <artifactId>struts2-core</artifactId>
- <version>2.5.18</version>
- </dependency>
Web.xml 配置 Struts2 拦截器
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
编写 struts.xml
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <package name="default" extends="struts-default">
- <action name="hello" class="com.jimisun.action.TestAction">
- <result name="hello">/Web-INF/jsp/hello.jsp</result>
- </action>
- </package>
- </struts>
编写控制器
- public class TestAction {
- public String execute() throws Exception {
- return "hello";
- }
- }
配置好以上步骤即可访问路径 http://localhost:8080/hello.action
Struts2 注解配置
注解配置 Struts2 完整示例源码下载
如果需要使用注解开发, 则需要增加 struts2-convention-plugin 的 Jar
- <!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-convention-plugin -->
- <dependency>
- <groupId>org.apache.struts</groupId>
- <artifactId>struts2-convention-plugin</artifactId>
- <version>2.5.18</version>
- </dependency>
那么在你的 Action 中就可以这样编写 Action, 不需要再到 struts.xml 中进行配置
- @ParentPackage("struts-default")
- @Namespace("/test")
- public class TestAction {
- @Action(value = "hello", results = {
- @Result(name = "hello", location = "/WEB-INF/jsp/hello.jsp")
- })
- public String hello() throws Exception {
- return "hello";
- }
- }
Struts2 的浏览器插件
在进行 Struts2 开发的时候随着项目的增大, 你所需要处理的路径和方法映射越多, 有时候会让你手忙脚乱, 而 struts2-config-browser-plugin 插件很好的帮你解决了这个问题, 只需要 Jar 包依赖即可
- <!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-config-browser-plugin -->
- <dependency>
- <groupId>org.apache.struts</groupId>
- <artifactId>struts2-config-browser-plugin</artifactId>
- <version>2.5.18</version>
- </dependency>
本章总结
Struts2 的起始配置比较简单, 但是 Struts2 其他相关配置就比较繁琐了, 不可掉以轻心
来源: https://www.cnblogs.com/jimisun/p/9945934.html