struts2 常量配置有3中方式,如下:
- 在struts.xml中使用<constant>元素配置常量
- struts.properties文件中配置常量
- 在web.xml文件中使用<init-param>元素配置常量
1 在struts.xml中使用<constant>元素配置常量
在struts.xml,文件中通过<constant>元素来配置常量,是最常用的方式。在struts.xml文件中通过<constant/>元素配置 常量时,需要指定两个必须的属性name 和 value
name:该属性指定了常量的常量名
value: 该属性指定了常量的值
示例如下:
<struts>
<!-- 设置默认编码 UTF-8 -->
<constant name="struts.i18n.encoding" value="UTF-8"/>
<!-- 设置开发模式 -->
<constant name="struts.devMode" value="true"></constant>
</struts>
2.在struts.properties 文件中配置常量
struts.properties文件是一个标准的properties文件,其格式是key-value对,即每个key对应一个value,key表示的是Struts2框架中的常量,而value则是其常量值。具体如下:
#设置默认编码集 UTF-8
struts.i18n.encoding=UTF-8
#设置action请求的扩展名为action或没有扩展名
struts.action.extension=action
#设置不使用开发模式
struts.devMode=false
#设置不开启动态调用
struts.enable.DynamicMethodInvocation=false
3.在web.xml文件中通过初始化参数配置常量
在web.xml文件配置中配置核心过滤器StrutsPrepareAndExecuteFilter时,通过初始化参数来配置常量。通过<filter>元素的<init-param>子元素指定,每个<init-param>元素配置了一个Struts2 常量,在web.xml文件中通过初始化参数配置常量方式。示例如下
<!-- 配置Struts2 核心控制器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
<init-param>
<param-name>struts.i18n.encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
struts2 框架加载常量有一定顺序,通常如下:
struts-default.xml:该文件保存在struts2-core-2.1.2.jar文件中
struts-plugin.xml:该文件保存在struts2-Xxx-2.1.2.jar灯Struts2插件jar文件中
struts.xml:该文件是web应用默认的Struts2的配置文件
struts.properties:该文件是struts2的默认配置文件
web.xml:该文件是web的配置文件
上面指定了Struts2框架搜索常量的顺序,但是如果在多个文件中配置同一个struts2常量,则后一个文件中配置的常量会覆盖前一个文件配置的常量.