1. 创建Web项目,导入Struts2核心库,如下图 所示
2. 在Web.xml中声明Struts2提供的过滤器,类名:org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>MyFisrtStruts</display-name> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
3. 创建struts.xml配置文件,定义Struts2中的Action对象
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="myPackage" extends="struts-default"> <action name="first"> <result>/first.jsp</result> </action> </package> </struts>
4. 创建index.jsp
<body>
keep improving!!!
<a href="first.action">request struts2 </a>
</body>
5. 创建first.jsp
<body>
keep improving!!!
</body>
6. 运行
备注:
1. 步骤3和步骤4中的action name要一致,否则错误如下图所示
2. Struts2的原理,如下图所示
基本简要流程如下:1、客户端浏览器发出HTTP请求。2、根据web.xml配置,该请求被FilterDispatcher接收。3、根据struts.xml配置,找到需要调用的Action类和方法, 并通过IoC方式,将值注入给Aciton。4、Action调用业务逻辑组件处理业务逻辑,这一步包含表单验证。5、Action执行完毕,根据struts.xml中的配置找到对应的返回结果result,并跳转到相应页面。6、返回HTTP响应到客户端浏览器。
参考文献:
1. http://tanpingpingiloveyou.iteye.com/blog/1635135
2. http://www.cnblogs.com/jy02444453/archive/2011/08/27/2155427.html