Struts2核心技術簡介,struts2核心技術
Struts2核心技術簡介
使用Struts2架構,只要注重以下三大元素:設定檔、對應檔和Action:
全域屬性檔案struts.properties:儲存系統啟動並執行一些參數變數,整個系統只有一個屬性檔案;
對應檔struts.xml:用於配置請求映射的Action和攔截器,可以有多個對應檔;
業務控制器Action:可以使用POJO(類似JavaBean)類,也可以整合ActionSupport,在該類中不僅可以取得表單資料,還可以取得上下文變數。以下是詳細說明:
1、全域屬性檔案struts.properties
struts.properties檔案主要定義系統的屬性,請看以下範例程式碼:
### Struts default properties###(can be overridden by a struts.properties file in the root of the classpath)######指定Struts2的配置類,預設為下面的配置,也可以通過繼承### Specifies the Configuration used to configure Struts ### one could extend org.apache.struts2.config.Configuration### to build one's customize way of getting the configurations parameters into Struts# struts.configuration=org.apache.struts2.config.DefaultConfiguration###設定預設的國際化地區資訊和國際化資訊內碼### This can be used to set your default locale and encoding scheme# struts.locale=en_USstruts.i18n.encoding=UTF-8###指定對象工廠類,也可以實現自己的工廠類### if specified, the default object factory can be overridden here### Note: short-hand notation is supported in some cases, such as "spring"### Alternatively, you can provide a com.opensymphony.xwork2.ObjectFactory subclass name here # struts.objectFactory = spring###當使用Spring的工廠類時,指定自動植入autoWrite的機制### specifies the autoWiring logic when using the SpringObjectFactory.### valid values are: name, type, auto, and constructor (name is the default)struts.objectFactory.spring.autoWire = name###使用Spring整合時,是否使用類緩衝,可選值有:true和false### indicates to the struts-spring integration if Class instances should be cached### this should, until a future Spring release makes it possible, be left as true### unless you know exactly what you are doing!### valid values are: true, false (true is the default)struts.objectFactory.spring.useClassCache = true###指定物件類型檢查器,可用值有“tiger”和“notiger”,也可以使用自己的類### if specified, the default object type determiner can be overridden here### Note: short-hand notation is supported in some cases, such as "tiger" or "notiger"### Alternatively, you can provide a com.opensymphony.xwork2.util.ObjectTypeDeterminer implementation name here### Note: By default, com.opensymphony.xwork2.util.DefaultObjectTypeDeterminer is used which handles type detection### using generics. com.opensymphony.xwork2.util.GenericsObjectTypeDeterminer was deprecated since XWork 2, it's### functions are integrated in DefaultObjectTypeDeterminer now.### To disable tiger support use the "notiger" property value here.#struts.objectTypeDeterminer = tiger#struts.objectTypeDeterminer = notiger###指定使用MIME-type multipart/form-data時的解析器### Parser to handle HTTP POST requests, encoded using the MIME-type multipart/form-data# struts.multipart.parser=cos# struts.multipart.parser=pellstruts.multipart.parser=jakarta# uses javax.servlet.context.tempdir by defaultstruts.multipart.saveDir=struts.multipart.maxSize=2097152###指定自訂的屬性檔案### Load custom property files (does not override struts.properties!)# struts.custom.properties=application,org/apache/struts2/extension/custom###URL與Action映射處理器### How request URLs are mapped to and from actions#struts.mapper.class=org.apache.struts2.dispatcher.mapper.DefaultActionMapper###指定URL的副檔名,可以指定多個副檔名,用逗號分隔,例如action、jnlp、do### Used by the DefaultActionMapper### You may provide a comma separated list, e.g. struts.action.extension=action,jnlp,dostruts.action.extension=do###被FilterDispatcher所使用,true表示Struts serves static content來自於內部jar### Used by FilterDispatcher### If true then Struts serves static content from inside its jar. ### If false then the static content must be available at <context_path>/strutsstruts.serve.static=true###是否Struts過濾器中提供的靜態內容應該被瀏覽器緩衝到頭部屬性中### Used by FilterDispatcher### This is good for development where one wants changes to the static content be### fetch on each request. ### NOTE: This will only have effect if struts.serve.static=true### If true -> Struts will write out header for static contents such that they will### be cached by web browsers (using Date, Cache-Content, Pragma, Expires)### headers).### If false -> Struts will write out header for static contents such that they are### NOT to be cached by web browser (using Cache-Content, Pragma, Expires### headers)struts.serve.static.browserCache=true###是否允許動態方法引動過程,如果為true,則可以配置如下的<action>參數映射### mappings, such as <action name="*/*" method="{2}" class="actions.{1}">### Set this to false if you wish to disable implicit dynamic method invocation### via the URL request. This includes URLs like foo!bar.action, as well as params### like method:bar (but not action:foo). ### An alternative to implicit dynamic method invocation is to use wildcard ### mappings, such as <action name="*/*" method="{2}" class="actions.{1}">struts.enable.DynamicMethodInvocation = true###是否在action名稱中允許“/”### Set this to true if you wish to allow slashes in your action names. If false,### Actions names cannot have slashes, and will be accessible via any directory### prefix. This is the traditional behavior expected of WebWork applications.### Setting to true is useful when you want to use wildcards and store values### in the URL, to be extracted by wildcard patterns, such as ### <action name="*/*" method="{2}" class="actions.{1}"> to match "/foo/edit" or ### "/foo/save".struts.enable.SlashesInActionNames = false###是否可以用替代的文法%{}代替tags### use alternative syntax that requires %{} in most places### to evaluate expressions for String attributes for tagsstruts.tag.altSyntax=true###是否為Struts開發模式### when set to true, Struts will act much more friendly for developers. This### includes:### - struts.i18n.reload = true### - struts.configuration.xml.reload = true### - raising various debug or ignorable problems to errors### For example: normally a request to foo.action?someUnknownField=true should### be ignored (given that any value can come from the web and it### should not be trusted). However, during development, it may be### useful to know when these errors are happening and be told of### them right away.struts.devMode = false###是否國際化資訊自動載入### when set to true, resource bundles will be reloaded on _every_ request.### this is good during development, but should never be used in productionstruts.i18n.reload=false### Standard UI theme### Change this to reflect which path should be used for JSP control tag templates by defaultstruts.ui.theme=xhtmlstruts.ui.templateDir=template#sets the default template type. Either ftl, vm, or jspstruts.ui.templateSuffix=ftl###在struts.xml 檔案更改時,是否允許重載### Configuration reloading### This will cause the configuration to reload struts.xml when it is changedstruts.configuration.xml.reload=false###velocity設定檔路徑,預設為velocity.properties### Location of velocity.properties file. defaults to velocity.propertiesstruts.velocity.configfile = velocity.properties###Cvelocity的context列表### Comma separated list of VelocityContext classnames to chain to the StrutsVelocityContextstruts.velocity.contexts =###velocity工具盒的位置### Location of the velocity toolboxstruts.velocity.toolboxlocation=### used to build URLs, such as the UrlTagstruts.url.http.port = 80struts.url.https.port = 443### possible values are: none, get or allstruts.url.includeParams = get###載入附加的國際化屬性檔案(不包含.properties)### Load custom default resource bundlesstruts.custom.i18n.resources=com.demo.struts2.resources.ApplicationResources### workaround for some app servers that don't handle HttpServletRequest.getParameterMap()### often used for WebLogic, Orion, and OC4Jstruts.dispatcher.parametersWorkaround = false### configure the Freemarker Manager class to be used### Allows user to plug-in customised Freemarker Manager if necessary### MUST extends off org.apache.struts2.views.freemarker.FreemarkerManager#struts.freemarker.manager.classname=org.apache.struts2.views.freemarker.FreemarkerManager### Enables caching of FreeMarker templates### Has the same effect as copying the templates under WEB_APP/templatesstruts.freemarker.templatesCache=false### Enables caching of models on the BeanWrapperstruts.freemarker.beanwrapperCache=false### See the StrutsBeanWrapper javadocs for more informationstruts.freemarker.wrapper.altMap=true### configure the XSLTResult class to use stylesheet caching.### Set to true for developers and false for production.struts.xslt.nocache=false###struts自動載入的設定檔列表### A list of configuration files automatically loaded by Strutsstruts.configuration.files=struts-default.xml,struts-plugin.xml,struts.xml### Whether to always select the namespace to be everything before the last slash or notstruts.mapper.alwaysSelectFullNamespace=falseView Code
2、對應檔struts.xml
Struts2架構的核心設定檔時Struts.xml,該檔案主要負責管理Struts架構的業務控制器Action。該檔案包含唯一的根項目<struts>,可以在該元素中添加子標籤來實現自己的配置。一般開發主要用到如下的七個配置功能:
(1)屬性定義元素<constant>
可以使用<constant>標籤來定義一個屬性,該屬性與struts.properties中屬性重名,並覆蓋struts.properties中該屬性的值。這樣做的好處是,如果使用了多個對應檔時,允許每一個檔案都使用不同的屬性。
(2)匯入子檔案元素<include>
使用<include>標籤來匯入一個子檔案,子檔案與struts.xml有同樣的結構,使用相同的配置文法。通過這種方式提供了一種模組化的方式來管理struts.xml檔案。
(3)包定義元素<package>
<package>定義了一組<action>和攔截器元素,可以定義多個<action>元素,name表示包的名字,extends屬性工作表示繼承自struts-default.xml中所定義的包的名字。
(4)Action映射配置元素<action>
Action mapping是架構中的基本工作單元,架構通過對請求路徑進行映射來決定由哪個Action來處理請求。
(5)Result配置元素<result>
Action類處理完一個請求後會返回一個字串,這個字串將被用來選擇一個<result>元素。通常一個action mapping會有多個<result>,代表各個可能不同的結果。
(6)配置全域對應元素<global-results>
定義在<action>元素裡面的<result>我們可以稱之為局部<result>,除此之外我們還可以定義全域的<result>,這些全域的<result>會悲哀多個<action>所共用。架構會首先尋找嵌套在<action>元素中的<result>,如果沒有匹配的就去全域<result>中去尋找。
(7)配置攔截器<interceptors>
通過使用攔截器,我們可以在Action中的方法執行之前先執行一些我們事先定義好的方法,也可以在Action中的方法執行之後立即執行一些我們事先定義好的方法。
下面請看一個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> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="false" /> <include file="example.xml"/> <!-- Add packages here --> <package name="main" extends="struts-default"> <action name="test" class="com.demo.struts2.actions.TestAction"> <result name="success">success.jsp</result> <result name="input">input.jsp</result> </action> </package></struts>View Code
3、業務控制器Action
使用Struts2架構,不需要開發ActionForm類,主要注意一下三點:
Action可以是任意的POJO(類似JavaBean)類
一般繼承ActionSupport類
可以在Action中訪問上下文變數