欢迎浏览Java工程师SSH教程从零打造在线网盘系统系列教程,本系列教程将会使用SSH(Struts2+Spring+Hibernate)打造一个在线网盘系统,本系列教程是从零开始,因此会详细以及着重地阐述SSH三个框架的基础知识,第四部分将会进入项目实战,若是您已经对SSH框架有所掌握,那么能够直接浏览第四章,源码均提供在GitHub/ssh-network-hard-disk上供你们参阅html
Struts2是一个基于MVC设计模式的Web应用框架,它本质上至关于一个servlet,在MVC设计模式中,Strus2做为控制器(Controller)来创建模型与视图的数据交互。Struts2使用了大量的拦截器来处理用户请求,从而将业务逻辑控制器和ServletAPI分离git
包含execute方法的POJO既能够做为控制器,即一个简单的JAVA类包含一个execute()方法就能够做为控制器,同时控制器具备封装客户端请求参数的能力.github
public class TestAction { public String execute() throws Exception { return "test"; } }
XML配置完整工程示例源码下载
导入struts依赖jarweb
<!-- 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拦截器apache
<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.actionapp
注解配置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中进行配置ssh
@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-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其余相关配置就比较繁琐了,不可掉以轻心