Struts2中配置常量总共有3种方式:
① 通过struts.properties文件。
② 通过struts.xml配置文件。
③ 通过Web应用的web.xml文件。
Struts2的所有配置文件,包括struts-default.xml,struts-plugin.xml,甚至用户自定义的、只要能被Struts2加载的配置文件,都可以使用常量配置的方式来配置Struts2常量。
如下struts.xml配置片段配置了一个常量,该常量即可替代struts.properties文件中的配置属性。
1
2
3
4
5
6
7
8<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <constant name="struts.custom.i18n.resources" value="mess"/> ... </struts>
除此之外,当我们在web.xml文件中配置StrutsPrepareAndExecuteFilter时也可配置Struts2常量,此时采用为StrutsPrepareAndExecuteFilter配置初始化参数的方式来配置Struts2常量,如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://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>struts.custom.i18n.resources</param-name> <param-value>mess</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
通常,Struts2框架按照如下搜索顺序加载Struts2常量。
⑴ struts-default.xml
⑵ struts-plugin.xml
⑶ struts.xml
⑷ struts.properties
⑸ web.xml
上面指定了Struts2框架搜索常量的顺序,如果在多个文件中配置了同一个Struts2常量,则后一个文件中配置的常量值会覆盖前面文件中配置的常量值。
在不同文件中配置常量的方式是不一样的,但不管在哪个文件中,配置Struts2常量都需要指定两个属性:常量name和常量value,分别指定Struts2属性名和属性值。
包含其他配置文件:
在默认情况下,Struts2只自动加载类加载路径下的struts.xml、struts-default.xml和struts-plugin.xml三类文件。但随着应用规模的增大,系统中Action数量也大量增加,将导致struts.xml文件变得非常臃肿。
为了避免struts.xml文件过于庞大,提高struts.xml文件的可读性,我们可以将一个struts.xml文件分解成多个配置文件,然后在struts.xml中包含其他配置文件。
下面的struts.xml文件中就通过include手动导入了一个配置文件:struts-part1.xml文件,通过这种方式,就可以将Struts2的Action按照模块配置在多个配置文件中。
1
2
3
4
5
6
7
8<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <include file="struts-part1.xml"/> ... </struts>
被包含的struts-part1.xml文件是标准的Struts2配置文件,一样包含了dtd信息、Struts2配置文件的根元素等信息。
最后
以上就是友好黄蜂最近收集整理的关于Struts2(2):Struts2中配置常量的3种方式及包含其他配置文件的全部内容,更多相关Struts2(2):Struts2中配置常量内容请搜索靠谱客的其他文章。
发表评论 取消回复