一、添加Struts2依賴的jar包
- commons-fileupload-1.3.1.jar:Struts文件的上傳與下載
- commons-io-2.2.jar:文件讀取
- commons-lang3-3.2.jar:爲java.lang包提供擴展
- freemarker-2.3.22.jar:模板引擎,是一個基於模板生成文本輸出的通用工具
- ognl-3.0.6.jar:支持OGNL表達式
- struts2-core-2.3.24.1.jar:Struts2的核心包
- xwork-core-2.3.24.1.jar:xwork的核心包
- javassist-3.11.0.GA.jar:分析、編輯和創建Java字節碼的類庫
二、配置過濾器
修改web.xml配置文件,配置Struts2過濾器,負責攔截用戶請求,從而交給Struts2處理
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Struts2_Data</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- Struts2過濾器配置 -->
<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>
三、使用Struts2輸出的三種方式
首先創建struts.xml,內容如下:
<?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>
<!--這裏編寫Struts2配置-->
</struts>
action簡介:
- 1、自己編寫Action類
1.action配置
<action name="hello01" class="com.pb01.demo01.HelloAction" method="execute">
<result name="success">/jsp/01_使用Struts2輸出/hello.jsp</result>
</action>
2.action類代碼
package com.pb01.demo01;
public class HelloAction {
public String execute() {
return "success";
}
}
3.視圖界面略
4.訪問路徑及結果
- 2、實現Action接口
1.action配置
<action name="hello02" class="com.pb01.demo02.HelloAction">
<result>/jsp/01_使用Struts2輸出/hello.jsp</result>
</action>
2.action類
package com.pb01.demo02;
import com.opensymphony.xwork2.Action;
/**
*實現Action接口
**/
public class HelloAction implements Action {
@Override
public String execute() throws Exception {
return "success";
}
}
3.視圖頁面略
- 3、繼承ActionSupport類
1.action配置
<action name="hello03" class="com.pb01.demo03.HelloAction">
<result>/jsp/01_使用Struts2輸出/hello.jsp</result>
</action>
2.action類
package com.pb01.demo03;
import com.opensymphony.xwork2.ActionSupport;
/**
*繼承ActionSupport
*/
public class HelloAction extends ActionSupport {
@Override
public String execute() throws Exception {
return SUCCESS;
}
}
3.視圖界面略
四、總結
實際開發中,推薦使用第三種方式,因爲ActionSupport類已經實現了很多常用的功能,如國際化、輸入驗證等。