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_US struts.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=pell struts.multipart.parser=jakarta # uses javax.servlet.context.tempdir by default struts.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,do struts.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>/struts struts.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 tags struts.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 production struts.i18n.reload=false ### Standard UI theme ### Change this to reflect which path should be used for JSP control tag templates by default struts.ui.theme=xhtml struts.ui.templateDir=template #sets the default template type. Either ftl, vm, or jsp struts.ui.templateSuffix=ftl ###在struts.xml 文件更改時,是否允許重載 ### Configuration reloading ### This will cause the configuration to reload struts.xml when it is changed struts.configuration.xml.reload=false ###velocity配置文件路徑,默認為velocity.properties ### Location of velocity.properties file. defaults to velocity.properties struts.velocity.configfile = velocity.properties ###Cvelocity的context列表 ### Comma separated list of VelocityContext classnames to chain to the StrutsVelocityContext struts.velocity.contexts = ###velocity工具盒的位置 ### Location of the velocity toolbox struts.velocity.toolboxlocation= ### used to build URLs, such as the UrlTag struts.url.http.port = 80 struts.url.https.port = 443 ### possible values are: none, get or all struts.url.includeParams = get ###加載附加的國際化屬性文件(不包含.properties) ### Load custom default resource bundles struts.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 OC4J struts.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/templates struts.freemarker.templatesCache=false ### Enables caching of models on the BeanWrapper struts.freemarker.beanwrapperCache=false ### See the StrutsBeanWrapper javadocs for more information struts.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 Struts struts.configuration.files=struts-default.xml,struts-plugin.xml,struts.xml ### Whether to always select the namespace to be everything before the last slash or not struts.mapper.alwaysSelectFullNamespace=false View 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中訪問上下文變量