struts2優勢
- 與Servlet API 耦合性低。無侵入式設計
- 提供了攔截器,利用攔截器能夠進行AOP編程,實現如權限攔截等功能
- 支持多種表現層技術,如:JSP、freeMarker、velocity等
- 輸入校驗能夠對指定方法進行校驗,解決了struts1長久之痛
- 提供了全局範圍、包範圍和Action範圍的國際化資源文件管理實現
搭建struts2開發環境
1. 導包
- struts2-core-2.x.x.jar:核心類庫
- xwork-2.x.x.jar:XWork類庫,struts2在其上構建
- ognl-2.6.x.jar:對象圖導航語言,struts2經過其讀寫對象屬性
- freemarker-2.3.x.jar:struts2的UI標籤的模板使用FreeMarker編寫
- commons-logging-1.1.x.jar:ASF出品的日誌包,struts2使用這個日誌包來支持log4j和jdk1.4+的日誌目錄
- commons-fileupload-1.2.1.jar:文件上傳組件,2.1.6後必須加入此文件
2. 配置web.xml文件
<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>
- struts2框架經過Filter啓動
- StrutsPrepareAndExecuteFilter的init()方法中將會讀取類路徑下默認的配置文件struts.xml完成初始化操做
- struts2讀取到struts.xml的內容後,以JavaBean形式存放在內存中,之後struts2對用戶的每次請求處理將使用內存中的數據,而不是每次都讀取struts.xml文件
3. 編寫Action類,這是咱們的邏輯控制器
package com.liuyong666.action;
public class HelloWorldAction {
private String msg;
public String getMessage() {
return msg;
}
public String execute(){
msg = "個人第一個struts2應用";
return "success";
}
}
4. 配置src/struts.xml,核心配置文件中配置action
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="liuyong666" namespace="/test" extends="struts-default">
<action name="helloworld" class="com.liuyong666.action.HelloWorldAction" method="execute" >
<result name="success">/WEB-INF/page/hello.jsp</result>
</action>
</package>
</struts>
- 在struts2中使用包管理Action
- 配置包時必須指定name屬性,能夠任意名,但必須惟一
- namespace定義該包的命名空間,爲訪問該包下Action的路徑的一部分,如上邊例子的訪問路徑爲:/test/helloworld.action。也能夠不配置
- 繼承struts-default包,該包擁有struts2提供的核心功能,擁有各類攔截器。
- 包可經過abstract="true"定義爲抽象包,抽象包中不能包含action