天天看點

struts2每日一記1

1.struts2是作用在表現的基于模型-視圖-控制器模式的開源架構,即mvc架構;

2.struts為struts1注入了webwork的設計理念,統一了struts1和webwork架構,是以struts1和webwork将不再有新的版本推出。

3.mvc設計模式:mvc思想将應用分成3個基本部分,model,view,controllers這三個部分之間耦合性非常小,進而提高了應用的可擴充性和可維護性。

4.struts1架構的複習:struts的大緻流程》》将其分成兩個部分:1.伺服器啟動時,啟動中央控制器(在web.xml中配置的ActioServlet)。

2.當浏覽器端發送請求到伺服器,struts1的中央控制器接收請求後根據struts-config.xml中尋找對應的映射關系。若找到就到action裡執行相應的方法,去執行相應的邏輯操作,若找不到就傳回錯誤資訊到jsp頁面。

5.struts2的架構 struts2的大緻流程:浏覽器發送請求(*.action),中央控制器(過濾器)接收請求,去配置檔案(*.properties,*.xml)中找相應的配置和action,action會去器代 理 的action中找到相應的包,包中若定義了攔截器,則先通過攔截器到達到action,action通過調用相應的方法處理邏輯業務,然後通過層層攔截器傳回給中央控制器,中央控制器将處理結果傳回給view(jsp),通過處理夠将其展現給浏覽器的用戶端。

下面開始sturts2的具體工作:1搭建struts2環境 a.加入struts2的jar,

上傳檔案

commons-fileupload-1.2.1.jar

commons-io-1.3.2.jar

模闆語言

freemarker-2.3.16.jar

分析、編輯和建立Java位元組碼的類庫

javassist-3.7.ga.jar

核心庫

ognl-3.0.jar

xwork-core-2.2.1.1.jar

struts2-core-2.2.1.1.jar

可選

使用Struts sx标簽

struts2-dojo-plugin-2.1.8.jar

資料校驗

commons-validator-1.3.1.jar

與Spring整合

struts2-spring-plugin-2.2.1.1.jar

2.web.xml配置struts2中央控制器(過濾器),可以從

struts2-blank.war\WEB-INF\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>

c.

在src下定義struts.xml,可以從struts2-blank.war\WEB-INF\src\java\struts.xml下拷貝,清空原有的配置

<?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>

</struts>

d.部署測試運用

2.第一個Struts應用程式,運作/hello.action,請求通過Action調轉到jsp頁面顯示Hello World

在Struts2中定義Action來代替Serlvlet處理請求。思路相似,寫法不同

編寫Servlet類繼承HttpServlet 編寫Action 繼承Action 編寫Action
重寫services方法處理請求 定義execute方法 定義任何方法處理請求
在services方法内跳轉 在struts-config.xml中定義跳轉 在struts.xml中定義跳轉
在web.xml中注冊servlet 在struts-config.xml中注冊action 在struts.xml中注冊action

a.編寫hello.jsp

b.編寫HelloWorldAction

public class HelloWorldAction {

public String execute() throws Exception {

return "success";

}

}

c.編寫struts.xml

<struts>

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

<action name="hello"

class="com.puckasoft.web.action.HelloWorldAction" method="execute">

<result name="success" type="dispatcher">/hello.jsp</result>

</action>

</package>

</struts>

當通路/hello時,Struts2調用HelloWorldAction類的execute方法處理請求。

Execute方法傳回success字元串,Struts2根據success查找對應的路徑/hello.jsp跳轉

d.測試運用

3. Action的三種寫法

a.POJO Actions - 任意的類都可以作為Action,甚至不需要實作任何接口,也不需要繼承某個父類

public class HelloWorldAction {

public String execute() throws Exception {

return "success";

}

}

b.實作 com.opensymphony.xwork2.Action 接口,這種方式可以借助于Action接口中定義的方法來規範請求的處理,定義的常量來規範方法的傳回值。

Action源碼如下

package com.opensymphony.xwork2;

public interface Action {

 public static final String SUCESS= "success";

 public static final String NONE = "none";

 public static final String ERROR = "error";

 public static final String INPUT = "input";

 public static final String LOGIN = "login";

 public String execute() throws Exception;

}

public class HelloWorldAction2 implements Action {

public String execute() throws Exception {

return Action.SUCCESS;

}

}

c.繼承 com.opensymphony.xwork2.ActionSupport 類。 ActionSupport類實作了Action接口,同時提供了國際化和校驗的方法,這樣可以大大簡化Action的編寫,在工作中,通常采用這種方式完成Action的定義。

ActionSupport源碼如下

public class ActionSupport implements Action, Validateable, ValidationAware, TextProvider, LocaleProvider, Serializable {

 public String execute() throws Exception {

 return SUCCESS;

}//成功跳轉的方法

 public void valiadate() {

}//驗證通路的方法

public void addFieldError(String fieldName, String errorMessage) {

 ...

}//檔案出錯方法

 public Locale getLocale() {//國際化的方法,找到本地路徑

 ...

}

public String getText(String aTextName) {//取國際化資源

 ...

}

}

public class HelloWorldAction3 extends ActionSupport {

}

struts2的Action非單例,每次使用者請求到來以後都會産生一個新的執行個體,而struts1的Action 是單例的,在編寫struts1的Action的時候務必要小心線程安全問題 , 而struts2中該問題不複存在

注:如何檢視架構源碼

點選Attach Source… 按鈕,點選 External Folder ... 按鈕,彈出檔案對話框.選擇源碼存放的路徑,再點選Apply按鈕完成操作。

Struts2的源碼在struts-2.2.1.1\src\core\src\main\java目錄下

Webwork的源碼在struts-2.2.1.1\src\xwork-core\src\main\java 目錄下

4.配置檔案介紹

在tomcat的config目錄下有個全局web.xml ,對所有部署在tomcat中的webapp都有效。

在Struts2_01_Helloworld的WebRoot/WEB-INF目錄下也有一個局部的web.xml,隻對該工程有效。Struts2也有這樣的設計。

Struts2配置檔案:

struts-default.xml :struts2全局配置檔案, struts2架構啟動時會自動加載該檔案

位置:struts2-core-2.2.1.1.jar/struts-default.xml

作用:定義bean和一個抽象的包。包中定義了傳回類型、攔截器、攔截器棧、預設的攔截器和預設的Action

<struts>

 <bean class="com.opensymphony.xwork2.ObjectFactory" name="xwork" />

. . .

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

 <result-types>

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

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

 </result-types>

 <interceptors>

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

 <interceptor name="fileUpload" class="org.apache.struts2.interceptor.FileUploadInterceptor"/>

 <interceptor name="i18n" class="com.opensymphony.xwork2.interceptor.I18nInterceptor"/>

 <interceptor name="modelDriven" class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/>

 <interceptor name="params" class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/>

  . . .

 <interceptor-stack name="basicStack">

 <interceptor-ref name="exception"/>

 <interceptor-ref name="servletConfig"/>

 <interceptor-ref name="prepare"/>

 <interceptor-ref name="checkbox"/>

 <interceptor-ref name="multiselect"/>

 <interceptor-ref name="actionMappingParams"/>

 <interceptor-ref name="params">

 <param name="excludeParams">dojo\..*,^struts\..*</param>

 </interceptor-ref>

 <interceptor-ref name="conversionError"/>

 </interceptor-stack>

. . .

 <interceptor-stack name="defaultStack">

 <interceptor-ref name="exception"/>

 <interceptor-ref name="alias"/>

 <interceptor-ref name="servletConfig"/>

 <interceptor-ref name="i18n"/>

 <interceptor-ref name="prepare"/>

 <interceptor-ref name="chain"/>

 <interceptor-ref name="debugging"/>

 <interceptor-ref name="scopedModelDriven"/>

 <interceptor-ref name="modelDriven"/>

 <interceptor-ref name="fileUpload"/>

 <interceptor-ref name="checkbox"/>

 <interceptor-ref name="multiselect"/>

 <interceptor-ref name="staticParams"/>

 <interceptor-ref name="actionMappingParams"/>

 <interceptor-ref name="params">

 <param name="excludeParams">dojo\..*,^struts\..*</param>

 </interceptor-ref>

 <interceptor-ref name="conversionError"/>

 <interceptor-ref name="validation">

 <param name="excludeMethods">input,back,cancel,browse</param>

 </interceptor-ref>

 <interceptor-ref name="workflow">

 <param name="excludeMethods">input,back,cancel,browse</param>

 </interceptor-ref>

 </interceptor-stack>

 </interceptors>

 <default-interceptor-ref name="defaultStack"/>

 <default-class-ref class="com.opensymphony.xwork2.ActionSupport" />

 </package>

</struts>

struts.xml : 使用者自定義,

位置:src /struts.xml

作用:定義WebApp中的各種Action、傳回結果、異常處理和攔截器資訊

default.properties:Struts2全局常量檔案,架構啟動時會自動加載該檔案

位置:struts2-core-2.2.1.1.jar/org/apache/struts2/default.properties

作用:定義系統配置資訊

# struts.configuration=org.apache.struts2.config.DefaultConfiguration

# struts.locale=en_US

struts.i18n.encoding=UTF-8

# struts.objectFactory = spring

struts.objectFactory.spring.autoWire = name

struts.objectFactory.spring.useClassCache = true

struts.objectFactory.spring.autoWire.alwaysRespect = false

#struts.objectTypeDeterminer = tiger

#struts.objectTypeDeterminer = notiger

# struts.multipart.parser=cos

# struts.multipart.parser=pell

struts.multipart.parser=jakarta

# uses javax.servlet.context.tempdir by default

struts.multipart.saveDir=

struts.multipart.maxSize=2097152 

# struts.custom.properties=application,org/apache/struts2/extension/custom

#struts.mapper.class=org.apache.struts2.dispatcher.mapper.DefaultActionMapper

struts.action.extension=action,,

struts.serve.static=true

struts.serve.static.browserCache=true

struts.enable.DynamicMethodInvocation = true

struts.enable.SlashesInActionNames = false

struts.tag.altSyntax=true

struts.devMode = false

struts.i18n.reload=false

struts.ui.theme=xhtml

struts.ui.templateDir=template

#sets the default template type. Either ftl, vm, or jsp

struts.ui.templateSuffix=ftl

struts.configuration.xml.reload=false

struts.velocity.configfile = velocity.properties

struts.velocity.contexts =

struts.velocity.toolboxlocation=

struts.url.http.port = 80

struts.url.https.port = 443

struts.url.includeParams = none

# struts.custom.i18n.resources=testmessages,testmessages2

struts.dispatcher.parametersWorkaround = false

#struts.freemarker.manager.classname=org.apache.struts2.views.freemarker.FreemarkerManager

struts.freemarker.templatesCache=false

struts.freemarker.beanwrapperCache=false

struts.freemarker.wrapper.altMap=true

struts.freemarker.mru.max.strong.size=100

struts.xslt.nocache=false

struts.mapper.alwaysSelectFullNamespace=false

struts.ognl.allowStaticMethodAccess=false

struts.el.throwExceptionOnFailure=false

struts.ognl.logMissingProperties=false

struts.ognl.enableExpressionCache=true

struts.properties: 使用者自定義

位置:src/struts.properties

作用:覆寫系統配置資訊

5.Action的通路路徑與常量配置方法

Action的通路路徑是由Action的名字,所在包的命名空間,和常量struts.action.extension共同決定的

struts.action.extension的預設值是action, ,

也就是說要通路配置檔案中的Action 可以運作/helloworld 和 /helloworld.action

指定請求Action的字尾為do,action後,就隻能通過/helloworld.do 和helloworld.action 通路Action了

常量配置:

Struts2常量可以在web.xml,struts.xml,struts.properties等多處配置

以配置Action通路路徑的字尾為例子

a.在struts.xml中配置 

格式

<constant name="參數名" value="參數值"> 

代碼

<constant name="struts.action.extension" value="do"></constant>

b.在struts.properties中配置

格式

參數名=參數值 

代碼

struts.action.extension=action

c.在web.xml中的StrutsPrepareAndExecuteFilter中配置 

格式

<init-param>

<param-name>參數名</param-name> 

<param-value>參數值</param-value> 

</init-param>

代碼

<filter>

<filter-name>struts2</filter-name>

<filter-class>

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

</filter-class>

<init-param>

 <param-name>struts.action.extension</param-name>

 <param-value>do,action,,</param-value>

</init-param>

</filter>

不推薦在web.xml中配置,比較繁瑣,可讀性差

struts.xml和struts.properties選擇一種即可

練習:比較三種配置方法誰的優先級最高

加載順序如下:

1.struts2-core-2.2.1.1.jar/struts-default.xml(最最低)

2.struts2-core-2.2.1.1.jar/org/apache/struts2/default.properties(最低)

3.%class_path%/struts.xml(低)

4.%class_path%/struts.properties

5.web.xml(高)

練習:配置開發模式,struts.devMode的預設值是false,改成true時可以熱啟動web伺服器

配置字元集編碼為Utf-8

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

<constant name="struts.i18n.encoding" value="GBK"></constant>

6.struts.xml配置檔案詳解

Package标簽

在struts.xml 配置業務邏輯控制器, Action 必須要配置在package中,package的概念跟程式中包的概念類似。

功能:

解決了Action命名沖突

将功能類似的Action放到同一個包中,易于維護和管理。

配置格式:

<package name="" namespace="" extends=" " >

屬性:

name屬性(必選) : 包的名字,最好根據業務功能子產品命名,如果其他包要繼承該包,必須通過該屬性進行引用

namespace屬性(可選,預設為空字元串) : 定義該包的命名空間,命名空間作為通路該包下的Action的路徑的一部分

abstract屬性(可選) : 定義該包是否抽象,抽象時不能包含action。

extends屬性(可選) : 定義父包,可繼承父包的Action,攔截器和攔截器棧。通常繼承struts-default包, 因為它 定義了一些攔截器和跳轉類型。這些攔截器實作了 諸如将請求中把請求參數封裝到action、檔案上傳和資料驗證等等核心功能。

struts-default包定義在struts2-core-2.2.1.1.jar/struts-default.xml中

Action标簽

配置格式:

<action name=" " class=" " method=" ">

屬性:

name屬性(必填):action的名字

class屬性(選填,預設值為ActionSupport類):action的類名

method屬性(選填,預設值為execute):action的方法名

Result标簽

配置格式

<result name=" " type=" ">  </result>

name屬性(選填,預設值為success):result名字,和Action的execute方法的傳回對應

type屬性(選填,預設值為dispatcher):result類型,dispatcher為伺服器内部跳轉

簡化Struts配置

<action name="hello">

<result>/hello.jsp</result>

</action>

繼續閱讀