struts2重新梳理---Struts2核心配置

 StrutsPrepareAndExecuteFilter

 

<filter>

    <filter-name>Struts2</filter-name>

        <filter-class>  org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

           </filter-class>

        <init-param>

              <param-name>packages</param-name>

             <param-value>

  cn.cstp.org.static,cn.cstp.org.xxx

  </param-value>

       </init-param>

       </filter>

       <filter-mapping>

               <filter-name>Struts2</filter-name>

               <url-pattern>/*</url-pattern>

      </filter-mapping>

 

StrutsPrepareAndExecuteFilter是核心控制器。它負責攔截由<url-pattern>/*</url-pattern>指定的所有用戶請求,當用戶請求到達時,該Filter會過濾用戶的請求。當請求轉入Struts 2框架處理時會先經過一系列的攔截器,然後再到Action。與Struts1不同,Struts2對用戶的每一次請求都會創建一個Action,所以Struts2中的Action是線程安全的。

StrutsPrepareAndExecuteFilter是對struts2較早版本的核心控制器FilterDispatcher(文檔建議,從struts2.1.3起不再使用該類)的替代,結合了StrutsPrepareFilter與StrutsExecuteFilter的功能

Struts.xml配置詳解

             在web應用程序中我們都是使用部署描述符來初始化一些資源如servlet、過濾器、監聽器等等,這個部署描述符就是那廣爲人知的web.xml了。同樣的,框架也使用一個配置文件來初始化它自己的資源,這些資源主要包括:

1.攔截器(Interceptor):對請求進行預處理和後加工;

2.Action Classes:負責調用商業邏輯和數據訪問層;

3.Results:負責返回視圖(view),如JSP頁面等等;

<struts>

    <constant name="struts.enable.DynamicMethodInvocation" value="false" />

  <!—常量配置-->

    <constant name="struts.devMode" value="false" />

    <include file=“example.xml”/><!—包含配置-->

    <package name="default" namespace="/" extends="struts-default">

        <!—包配置-->

        <action name="index">

            <result type="redirectAction">

                <param name="actionName">HelloWorld</param>

                <param name="namespace">/example</param>

            </result>

        </action>

    </package>

    <!-- Add packages here -->

</struts>

常量配置

p    我們可以通過定義一些能夠改變框架和插件行爲的關鍵設置來定製我們struts應用程序,而這些設置就是常量。常量扮演了兩個關鍵的角色:首先它們被用來覆蓋一些原有的默認設置,例如上傳文件的最大容量、框架是否處於開發模式等等;其次,常量還用來指定在一個類型(type)的多個實現中,哪個bean應該被選中。
p常量可以定義在多個文件中,默認情況下我們按照下面的順序來尋找常量,後面的將覆蓋前面的設置:

  struts-default.xml

  struts-plugin.xml

  struts.xml

  struts.properties

  web.xml

  前3個xml文件的格式是一樣的,因爲它們使用同一個DTD文件,在xml文件中Constant元素有兩個必須的屬性:name和value;在struts.properties文件中,每一個entry都被視爲一個常量;在web.xml文件中FilterDispatcher的初始化參數被載入爲常量

下面分別給出3中常量形式的例子。

  struts.xml文件中常量

        <struts> 

                   <constant name="struts.devMode" value="true" />

       </struts>

 struts.properties文件中常量

                  struts.devMode = true

  web.xml文件中常量

    <filter>

        <filter-name>struts</filter-name>    

       <filter-class>

            org.apache.struts2.dispatcher.FilterDispatcher

      </filter-class>

        <init-param>

          <param-name>struts.devMode</param-name>

          <param-value>true</param-value>

        </init-param>

    </filter>

包含配置

在大型項目開發中,可以將項目分解爲多個小模塊,每個模塊獨立開發和管理。我們可以爲每個模塊提供一個配置文件,然後對其進行配置,然後在struts.xml中使用include元素包含這些配置文件。
例如:

<include file="struts-chat.xml" />

<include file="struts-hangman.xml" />

<include file="struts-continuations.xml"/>

<include file="struts-tags.xml"/>

<include file="struts-validation.xml" />

 

包的配置

 Struts2中的包類似於java中的包,提供了將action、result、攔截器和攔截器棧組織成一個邏輯單元的一種方式,從而爲你簡化了維護工作,提高了重用性。
在struts.xml文件中,與web應用相關的設置都在包中定義,每一個包中都包含了將要用到的action、result、攔截器和攔截器棧。

屬性名

是否必須

描述信息

name

package的唯一標識,不允許同名

extends

指定要擴展的包

namespace

指定名稱空間

abstract

聲明包爲抽象的,這個package中不需要定義action

Struts-default.xml

       struts-default.xml文件是struts2框架默認加載的配置文件。它定義struts2一些核心的bean和攔截器。
這些攔截器是以key-value對的形式配置在struts-default.xml中,其中name是攔截器名字,就是後面使用該攔截器的引用點,value則指定攔截器的實現類。

 <package name="struts-default" abstract="true">

        <result-types>

            <result-type name="chain" class="com.opensymphony.xwork2.ActionChainResult"/>

            <result-type name="dispatcher" class="org.apache.struts2.dispatcher.ServletDispatcherResult" default="true"/>

            <result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult"/>

            <result-type name="httpheader" class="org.apache.struts2.dispatcher.HttpHeaderResult"/>

            <result-type name="redirect" class="org.apache.struts2.dispatcher.ServletRedirectResult"/>

            <result-type name="redirectAction" class="org.apache.struts2.dispatcher.ServletActionRedirectResult"/>

            <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>

            <result-type name="velocity" class="org.apache.struts2.dispatcher.VelocityResult"/>

            <result-type name="xslt" class="org.apache.struts2.views.xslt.XSLTResult"/>

            <result-type name="plainText" class="org.apache.struts2.dispatcher.PlainTextResult" />

        </result-types>

        <interceptors>

            <interceptor name="alias" class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/>

            <interceptor name="autowiring"

命名空間

 Package元素的namespace屬性可以將包中的action配置爲不同的命名空間,這樣就可以在不同的命名空間中使用同名action。Struts2框架使用命名空間和action的名字來標識一個action。
  默認的命名空間是空字符串””,也就是不設置namespace屬性時候的命名空間。
 我們在匹配一個action的時候,先到它指定的命名空間中去找,如果存在這個package,則在這個package中尋找名字爲test的action,當在該package下尋找不到action 時就會直接跑到默認namaspace的package裏面去尋找action(默認的命名空間爲空字符串“”),如果在默認namaspace的package裏面還尋找不到該action,頁面提示找不到action。

攔截器配置

    攔截器能在action被調用之前和被調用之後執行一些“代碼”。Struts2框架的大部分核心功能都是通過攔截器來實現的,如防止重複提交、類型轉換、對象封裝、校驗、文件上傳、頁面預裝載等等,都是在攔截器的幫助下實現的。每一個攔截器都是獨立裝載的(pluggable),我們可以根據實際的需要爲每一個action配置它所需要的攔截器,例如,一個action需要用來類型裝換、文件上傳,那麼我們可以給它設置相應的兩個攔截器。

 <interceptors>

            <interceptor-stack name="crudStack">

              <interceptor-ref name="checkbox" />

                <interceptor-ref name="params" />

        <interceptor-ref name="staticParams" />

                <interceptor-ref name="defaultStack" />

            </interceptor-stack>

 </interceptors>

 

配置Result

在Struts2框架中,一個完整的結果視圖配置文件如以下所示:

<action name=“Action名稱” class=“Action類路徑” method=“方法名”>

  <result name=“邏輯視圖名”  type=“結果類型”>

  <param name=“參數名”>參數值</param>

  </result>

</action>

有很多時候一個<result>初很多<action>使用,這時可以使用<global-results>標籤來定義全局的<result>,代碼如下:
<struts>
<package name="demo" extends="struts-default">
<global-results>
<result name="error">/error.jsp</result>
</global-results>
</package>
</struts>

Struts2支持多種結果類型,核心包下的struts-default.xml文件中可以找到其所支持的類型。

Struts.xml配置詳解—Bean配置

Struts2是個可以擴展的框架,框架的核心組件都是可以配置的,這些組件可以通過Struts2自身的依賴注入容器來裝配。開發時可以自己編寫組件來擴展框架功能,然後通過bean元素來配置組件。
在Struts-default.xml文件定義了struts2框架中可配置的組件

bean元素屬性

屬性名稱

是否必須

描述 信息

class

bean的類名

type

bean實現的主要接口

name

bean的名字,在具有相同Type屬性的bean中,該名字必須唯一

scope

bean的作用域,是default,singleton,request,session,thread中的一個

static

是否注入靜態方法,如果指定了type,static就不能爲true

optional

Bean是否可選

Bean的兩種配置方法

 1、框架的IoC容器創建bean的實例,然後將該實例注入到框架的內部對象中。

     第一種做法可以稱爲對象注入,它通常要用到bean的type屬性,告訴容器這個對象實現了哪個接口

   如果自己創建了ObjectFactory,則可以在struts-default.xml中作如下配置:

<struts>

    <bean type="com.opensymphony.xwork2.ObjectFactory"

    name="struts" class="org.apache.struts2.impl.StrutsObjectFactory" />

</struts>

  2 、通過bean的靜態方法向bean注入值
第二種做法使用值注入,允許不創建bean,而讓bean接受框架的常量。Bean使用值注入,必須使用static屬性,並將該屬性設置爲true。
例如:struts-default.xml文件中可以作如下配置:

<bean class=“com.opensymphony.xwork2.ObjectFactory” static=“true”/>

注:在實際開發中,很少使用<bean>元素。原因是Struts2本身提供的功能已經足夠強大,因此沒有必要去擴展或者替換Struts2的核心組建,自然也就用不到配置<bean>元素。

Struts-plugin.xml

Struts2提供了類似於Eclipse的插件機制來擴展自身的功能。
Struts-plugin.xml就是由插件使用的配置文件,該文件的結構和struts.xml相同,存放在插件的jar包中。
例如:如果我們想在項目中整合進spring的內容,則可以參考下面的操作。

struts2.Xspring集成

p將struts2-spring-plugin-2.0.x.jar文件包含到我們的應用中,放到WEB-INF/lib目錄下面即可。在這個插件包中有個struts-plugin.xml文件,它的內容如下:

<struts>  

          <bean type="com.opensymphony.xwork2.ObjectFactory" name="spring"  

              class="org.apache.struts2.spring.StrutsSpringObjectFactory" />  

          <constant name="struts.objectFactory" value="spring" />  

          <package name="spring-default">  

               <interceptors>  

                    <interceptor name="autowiring"  

class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>  

                <interceptor name="sessionAutowiring"  

class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor"/>  

              </interceptors>  

         </package>      

</struts>  

ActionSupport類的使用

 雖然使用現在的Action可以進行一系列的工作,但是想要更快更方便地進行開發,可以使Action類繼承com.opensymphony.xwork2.ActionSupport類。
 ActionSupport類是一個工具類,它已經實現了Action接口。除此之外,它還實現了Validateable接口,提供了數據校驗功能。通過繼承該ActionSupport類,可以簡化Struts 2的 Action開發。
 爲了更好的使用struts提供的內置功能,最好讓Action繼承ActionSupport類,主要是下面的情況:
1.讀取國際化信息
2.處理驗證錯誤
3.處理類型轉換錯誤

Action接口的使用

Action接口:

 

    Action接口定義了5個標準字符串常量:SUCCESS、NONE、ERROR、INPUT 、 LOGIN;1個execute()方法。
   這5個常量就是在日常開發中業務邏輯方法中返回的字符串,可以簡化和標準化execute方法的返回值。 execute()方法則是Action接口定義的一個默認的業務邏輯方法,在我們自定義的Action類中只需要重寫該方法即可,Struts2會默認地調用execute方法。

Action的傳值方式

 

  在Struts2中Action與外界交互,實現數值傳遞:字段驅動(Field-driven,有的地方也稱爲屬性驅動)方式傳值和模型驅動(Model-driven)方式傳值。
  不管屬性驅動還是模型驅動,Struts2框架都是通過攔截器負責提取請求參數,並將請求數據封裝到相應的Action實例的屬性或專門的模型的屬性。
   1. 字段驅動(屬性驅動)方式

  直接在Action裏定義各種Java基本類型的字段(屬性),使這些字段與表單數據相對應,並利用這些字段進行數據傳遞。前面我們做的示例都屬於字段驅動模式。

  2. 模型驅動方式

  模型驅動就是使用單獨的JavaBean模型進行數據傳遞。JavaBean所封裝的屬性與表單數據的屬性一一對應,JavaBean成爲數據傳遞的載體。

  Action類通過get*()方法來獲取模型,*爲具體的模型對象。

示例:修改用戶登錄驗證。

(1)新增一用戶域模型對象:Person.java

(2)Action類定義一個Person類型的域模型,使用getPerson()方法獲取模型對象。

(3)對於JSP頁面,如果是負責取值的,則格式必須爲“模型對象名.屬性名”;如果是負責傳值的,則格式爲“模型對象名.屬性名”或直接是“屬性名”。

public class LoginAction implements Action,ModelDriven<Person> {

  Person person=new Person();

  public String execute(){

  person.setName("tom");

  person.setPassword("123");

  return SUCCESS;

  }

  public Person getModel() { 

  return person;

  }

在Action中訪問Servlet API

 1.Struts2中的Action並沒有和任何Servlet API耦合,這樣框架更具靈活性,更易測試。
 2.但是,有時候我們必須訪問Servlet API,例如要使用request對象,或者跟蹤HTTP Session用戶狀態等。Struts2框架提供了兩種方式來訪問Servlet API。
 3.方式一:非IOC方式
   這種方式主要是利用了com.opensymphony.xwork2.ActionContext (當前Action的上下文對象)類以及org.apache.struts2.ServletActionContext類 通過這個類可以訪問Servlet    API。
  4.方式二IOC方式:
action類實現ServletRequestAware, SessionAware, ApplicationAware接口

 public String checkLogin(){    

       ActionContext ac=ActionContext.getContext();//獲得ActionContext    

       Map app=ac.getApplication();    

       ac.getSession().put("login",this.name);//把登錄名稱放入session中    

       ac.getApplication().put("login",this.name);//把登錄名稱放入application中    

       return SUCCESS;    

    }    

public class Login2Action extends ActionSupport 
  implements RequestAware , SessionAware, ApplicationAware{ 
  private Map request; 
  private Map session; 
  private Map application; 
  @Override 
  public String execute() throws Exception { 
  // TODO Auto-generated method stub 
  this.request.put("attribute", "request value servlet 不相關的 IoC "); 
  this.session.put("attribute", "session value servlet 不相關的 IoC "); 
  this.application.put("attribute", "application value servlet 不相關的 IoC "); 
  return SUCCESS; 
  } 
  @Override 
  public void setRequest(Map arg0) { 
  // TODO Auto-generated method stub 
  this.request = arg0; 
  } 
  @Override 
  public void setSession(Map arg0) { 
  // TODO Auto-generated method stub 
  this.session = arg0; 
  } 
  @Override 
  public void setApplication(Map arg0) { 
  // TODO Auto-generated method stub 
  this.application = arg0; 
  } 
  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章