从一个struts开发者的角度来看, 必须要关注的一个配置文件是 web.xml。 在这里,你可以控制整个struts框架和你的应用的配置. 默认的情况下, Struts 会加载一些内置的配置文件来配置自己, 然后用另外的配置文件来配置你的应用,尽管可能不需要编写除了web.xml以外的配置文件就可以开发一个struts应用。
你可以使用下列表格中的配置文件来配置你的struts应用. 有些配置文件可以被动态的加载. See Reloading configuration for more.
File | Optional | Location (relative to webapp) | Purpose |
---|---|---|---|
no | /WEB-INF/ | Web deployment descriptor to include all necessary framework components 包含了所有框架需要的组件的web配置文件 | |
yes | /WEB-INF/classes/ | Main configuration, contains result/view types, action mappings, interceptors, and so forth 主配置文件,包含了 result/view types, action mappings, interceptors等 | |
yes | /WEB-INF/classes/ | Framework properties 框架的参数 | |
yes | /WEB-INF/lib/struts2-core.jar | Default configuration provided by Struts Struts提供的默认配置文件 | |
yes | /WEB-INF/classes/ | Default macros referenced by | |
struts-plugin.xml | yes | At the root of a plugin JAR | Optional configuration files for Plugins in the same format as 可选的插件配置文件,格式如同struts.xml |
yes | /WEB-INF/classes/ | Override the default Velocity configuration |
Static Content
框架需要一些常用的静态组件 (JavaScript ,CSS 等等) 来为FilterDispatcher 过滤器服务. Any request starting with "/struts/
" denotes that static content is required, and then mapping the value after "/struts/
" to common packages in the framework and, optionally in the application's class path.
默认的, 将在下列的包中寻找:
- org.apache.struts2.static
- template
额外的包可以在配置文件中名为"packages"的参数列表中添加 (在 web.xml 为 FilterDispatcher 过滤器配置). 当添加额外的静态组件时, 要注意不要暴露了敏感的配置信息 (如数据库的密码).
Web.xml配置文件是Java Web应用的核心, 所以同样也是struts框架的核心.在web.xml中, Struts 定义了自己的过滤器 FilterDispatcher,这个Servlet Filter 类用来初始化Struts框架和处理所有请求. 这个过滤器可以包含一些初始化参数,来表明哪些额外的配置文件需要被加载,框架该有哪些行为等等。
除了FilterDispatcher, Struts 还提供了一个ActionContextCleanUp 类,当其他过滤器(如那些Sitemesh所使用的)需要访问一个已经初始化的struts框架时候,用来执行特殊的清理任务。
Key Initialization Parameters
- config - 一个用逗号隔开的列表表示需要被加载的xml文件
- actionPackages - 一个用逗号隔开的列表表示action需要用到的java包.
- configProviders - 一个用逗号隔开的列表表示实现了ConfigurationProvider 接口的java类,that should be used for building the Configuration.
- loggerFactory - 实现LoggerFactory接口的类的名字.
- * - 其他表示框架的常量的参数.
Simple Example
为struts配置为web.xml中关键的一点是添加一个过滤器和其映射关系。
<
web-app
id="WebApp_9" version="2.4"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<
filter
>
<
filter-name
>struts2</
filter-name
>
<
filter-class
>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</
filter-class
>
<
init-param
>
<
param-name
>actionPackages</
param-name
>
<
param-value
>com.mycompany.myapp.actions</
param-value
>
</
init-param
>
</
filter
>
<
filter-mapping
>
<
filter-name
>struts2</
filter-name
>
<
url-pattern
>/*</
url-pattern
>
</
filter-mapping
>
<!-- ... -->
</
web-app
>
|
Taglib Example
通常情况下,不需要也不推荐配置一个标签库. 标签库已经被包含在 struts-core.jar中
, 容器将会自动寻找到它.
如果因为一些原因需要在web.xml中配置一个标签库, 将TLD文件从META-INF文件中的 struts-core.jar
中提取出来, 然后在web.xml文件中添加一个taglib标记
<!-- ... -->
</
welcome-file-list
>
<
taglib
>
<
taglib-uri
>/s</
taglib-uri
>
<
taglib-location
>/WEB-INF/struts-tags.tld</
taglib-location
>
</
taglib
>
</
web-app
>
|
Custom FileManager and FileManagerFactory implementations
如果需要支持应用服务器中的特殊文件系统(如 JBoss中的VFS), 你使用自己的FileManager接口的实现类. 但必须在整个框架初始化前配置它。
使用 <init-param/>标记来使用自己的FileManager接口的实现类,如下:
<
filter
>
<
filter-name
>struts2</
filter-name
>
<
filter-class
>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</
filter-class
>
<
init-param
>
<
param-name
>struts.fileManager</
param-name
>
<
param-value
>com.company.MyFileManager</
param-value
>
</
init-param
>
</
filter
>
|
使用 <init-param/>标记来使用自己的FileManagerFactory实现类, 如:
<
filter
>
<
filter-name
>struts2</
filter-name
>
<
filter-class
>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</
filter-class
>
<
init-param
>
<
param-name
>struts.fileManagerFactory</
param-name
>
<
param-value
>com.company.MyFileManagerFactory</
param-value
>
</
init-param
>
</
filter
>
|
去看看默认的实现类 - DefaultFileManager.java 和 DefaultFileManagerFactory.java 来了解更多。
Struts框架的核心配置文件是默认的 struts.xml
文件,应该将它放在web项目的class路径之下 (通常为 /WEB-INF/classes
).
- 默认的配置文件会包含其它需要的配置文件。
-
struts-plugin.xml
文件可以放置在一个JAR文件中,应用会自动将其安装。所以一个模块可以是独立的,自动配置的。.- I如 Freemarker 和 Velocity 模块, 会自动从classpath中载入,所以一个模块可以独立写成一个JAR包.
A:可以,有两种方法。
1.使用<include>标记来引用另外的配置文件,会按先后顺序加载。
2.使用JAR包。一个模块会被加载至应用里,通过在JAR包里放置一个struts.xml,然后将JAR包放在classpath路径下。
所有的properties文件都可以用XML文件中的<constant>标记来表示.
Struts使用了一些properties文件,它们可以根据你的需要修改。当修改任何的properties时, 只需要在struts.properties文件中指定他的键和值。
properties文件 可以放在classpath里的任意地方,通常放在/WEB-INF/classes之下。
### Struts default properties
###(can be overridden by a struts.properties file in the root of the classpath)
###
### 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
### 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
### 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
### ensures the autowire strategy is always respected.
### valid values are: true, false (false is the default)
struts.objectFactory.spring.autoWire.alwaysRespect = false
### By default SpringObjectFactory doesn't support AOP
### This flag was added just temporally to check if nothing is broken
struts.objectFactory.spring.enableAopSupport = false
....
|
Struts2.jar
中包含了一个基本的配置文件 struts-default.xml. 它会被自动添加进struts.xml中,来提供标准的配置设置。
struts-default.xml 的部分内容:
<?
xml
version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
<
struts
>
<
constant
name="struts.excludedClasses"
value="
java.lang.Object,
java.lang.Runtime,
java.lang.System,
java.lang.Class,
java.lang.ClassLoader,
java.lang.Shutdown,
ognl.OgnlContext,
ognl.MemberAccess,
ognl.ClassResolver,
ognl.TypeConverter,
com.opensymphony.xwork2.ActionContext" />
<!-- this must be valid regex, each '.' in package name must be escaped! -->
<
constant
name="struts.excludedPackageNamePatterns" value="^java\.lang\..*,^ognl.*,^(?!javax\.servlet\..+)(javax\..+)" />
<
bean
class="com.opensymphony.xwork2.ObjectFactory" name="struts"/>
<
bean
type="com.opensymphony.xwork2.factory.ResultFactory" name="struts" class="org.apache.struts2.factory.StrutsResultFactory" />
.
.
.
<
bean
type="com.opensymphony.xwork2.security.ExcludedPatternsChecker" name="struts" class="com.opensymphony.xwork2.security.DefaultExcludedPatternsChecker" scope="default" />
<
bean
type="com.opensymphony.xwork2.security.AcceptedPatternsChecker" name="struts" class="com.opensymphony.xwork2.security.DefaultAcceptedPatternsChecker" scope="default" />
<
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-type
name="postback" class="org.apache.struts2.dispatcher.PostbackResult" />
</
result-types
>
<
interceptors
>
<
interceptor
name="alias" class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/>
<
interceptor
name="autowiring" class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/>
<
interceptor
name="chain" class="com.opensymphony.xwork2.interceptor.ChainingInterceptor"/>
....
<
interceptor
name="annotationWorkflow" class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor" />
<
interceptor
name="multiselect" class="org.apache.struts2.interceptor.MultiselectInterceptor" />
<
interceptor
name="deprecation" class="org.apache.struts2.interceptor.DeprecationInterceptor" />
<!-- Basic stack -->
<
interceptor-stack
name="basicStack">
<
interceptor-ref
name="exception"/>
<
interceptor-ref
name="servletConfig"/>
<
interceptor-ref
name="prepare"/>
<
interceptor-ref
name="checkbox"/>
<
interceptor-ref
name="datetime"/>
<
interceptor-ref
name="multiselect"/>
<
interceptor-ref
name="actionMappingParams"/>
<
interceptor-ref
name="params">
<
param
name="excludeParams">^action:.*,^method:.*</
param
>
</
interceptor-ref
>
<
interceptor-ref
name="conversionError"/>
<
interceptor-ref
name="deprecation"/>
</
interceptor-stack
>
<!-- Sample validation and workflow stack -->
<
interceptor-stack
name="validationWorkflowStack">
<
interceptor-ref
name="basicStack"/>
<
interceptor-ref
name="validation"/>
<
interceptor-ref
name="workflow"/>
</
interceptor-stack
>
....其他拦截器栈
<
interceptor-stack
name="completeStack">
<
interceptor-ref
name="defaultStack"/>
</
interceptor-stack
>
<!-- Sample execute and wait stack.
Note: execAndWait should always be the *last* interceptor. -->
<
interceptor-stack
name="executeAndWaitStack">
<
interceptor-ref
name="execAndWait">
<
param
name="excludeMethods">input,back,cancel</
param
>
</
interceptor-ref
>
<
interceptor-ref
name="defaultStack"/>
<
interceptor-ref
name="execAndWait">
<
param
name="excludeMethods">input,back,cancel</
param
>
</
interceptor-ref
>
</
interceptor-stack
>
</
interceptors
>
<
default-interceptor-ref
name="defaultStack"/>
<
default-class-ref
class="com.opensymphony.xwork2.ActionSupport" />
</
package
>
</
struts
>
|
文件中定义了所有默认的results 和 interceptors,还有 interceptor stacks 。注意package的name为"struts-default".
### Struts default properties
###(can be overridden by a struts.properties file in the root of the classpath)
###
### 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
### 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
### 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
### ensures the autowire strategy is always respected.
### valid values are: true, false (false is the default)
struts.objectFactory.spring.autoWire.alwaysRespect = false
### By default SpringObjectFactory doesn't support AOP
### This flag was added just temporally to check if nothing is broken
struts.objectFactory.spring.enableAopSupport = false
### 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
........
|
### Struts default properties
###(can be overridden by a struts.properties file in the root of the classpath)
###
### 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
### 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
### 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
### ensures the autowire strategy is always respected.
### valid values are: true, false (false is the default)
struts.objectFactory.spring.autoWire.alwaysRespect = false
### By default SpringObjectFactory doesn't support AOP
### This flag was added just temporally to check if nothing is broken
struts.objectFactory.spring.enableAopSupport = false
### 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
### 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-stream
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
### How request URLs are mapped to and from actions
#struts.mapper.class=org.apache.struts2.dispatcher.mapper.DefaultActionMapper
### Used by the DefaultActionMapper
### You may provide a comma separated list, e.g. struts.action.extension=action,jnlp,do
### The blank extension allows you to match directory listings as well as pure action names
### without interfering with static resources, which can be specified as an empty string
### prior to a comma e.g. struts.action.extension=, or struts.action.extension=x,y,z,,
struts.action.extension=action,,
### 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
### 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
### 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 = false
### 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
### Disables support for action: prefix
struts.mapper.action.prefix.enabled = false
### Blocks access to actions in other namespace than current with action: prefix
struts.mapper.action.prefix.crossNamespaces = false
### use alternative syntax that requires %{} in most places
### to evaluate expressions for String attributes for tags
struts.tag.altSyntax=true
### 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
### Change this to use a different token to indicate template theme expansion
struts.ui.theme.expansion.token=~~~
#sets the default template type. Either ftl, vm, or jsp
struts.ui.templateSuffix=ftl
### Configuration reloading
### This will cause the configuration to reload struts.xml when it is changed
### struts.configuration.xml.reload=false
### Location of velocity.properties file. defaults to velocity.properties
struts.velocity.configfile = velocity.properties
### Comma separated list of VelocityContext classnames to chain to the StrutsVelocityContext
struts.velocity.contexts =
### 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 = none
### Load custom default resource bundles
# struts.custom.i18n.resources=testmessages,testmessages2
### 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
### maxStrongSize for MruCacheStorage for freemarker, when set to 0 SoftCacheStorage which performs better in heavy loaded application
### check WW-3766 for more details
struts.freemarker.mru.max.strong.size=0
### configure the XSLTResult class to use stylesheet caching.
### Set to true for developers and false for production.
struts.xslt.nocache=false
### Whether to always select the namespace to be everything before the last slash or not
struts.mapper.alwaysSelectFullNamespace=false
### Whether to allow static method access in OGNL expressions or not
struts.ognl.allowStaticMethodAccess=false
### Whether to throw a RuntimeException when a property is not found
### in an expression, or when the expression evaluation fails
struts.el.throwExceptionOnFailure=false
### Logs as Warnings properties that are not found (very verbose)
struts.ognl.logMissingProperties=false
### Caches parsed OGNL expressions, but can lead to memory leaks
### if the application generates a lot of different expressions
struts.ognl.enableExpressionCache=true
### Indicates if Dispatcher should handle unexpected exceptions by calling sendError()
### or simply rethrow it as a ServletException to allow future processing by other frameworks like Spring Security
struts.handle.exception=true
|