1,bean元素的配置
struts2框架是一个具有高度可扩展性的java web框架,其主要核心组件不是以之间编写代码的方式下载代码里,而是通过配置文件以IoC控制反转 容器来管理这些组件。struts2可以通过配置方式管理其核心组件,从而允许开发者很方便的扩展这些核心组件。
Bean在struts.xml中的配置格式如下:
<!-- Bean配置 -->
<bean name="Bean的名字" class="自定义的组件类"></bean>
<bean/>元素的常用属性如下:
1,name:指定Bean实例化对象的名字,对于相同类型的多个Bean实例,其对应的name属性值不能相同。
2,class :指定Bean实例的实现类
3,type:指定Bean实例实现的struts2规范,该规范通常是通过某个接口体现的,因此该属性的值通常是一个struts2接口。
4,scope:指定Bean的作用域。
5,optional:指定bean是否是一个可选项的bean。
6,static:指定允许不创建bean实例,而是让Bean接受框架常量,这时属性设为true。但是当指定type属性时,该属性不能设为true。
2,常量constant的配置
常量的配置格式如下:
<!-- 常量配置 -->
<constant name="资源文件" value="资源文件名字"></constant>
<constant/>元素常用属性如下:
1,name:指定常量属性的名字
2,value:指定常量的值
例如在struts.xml文件中配置国际化文件名和字符集的编码方式为gb2312,代码如下:
<!-- 常量配置 ,指定struts2国际化资源文件的名字是messageResource-->
<constant name="struts.custom.i18n.resources" value="messageResource"></constant>
<!-- 常量配置 ,指定国际化编码方式-->
<constant name="struts.custom.i18n.encoding" value="gb2312"></constant>
在struts.properties文件中相应配置代码如下:
struts.custom.i18n.resources=messageResource
struts.custom.i18n.encoding=gb2312
在web.xml中相应的配置代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>messageResource</param-value>
<!-- 指定编码方式常量 -->
<param-name>struts.custom.i18n.encoding</param-name>
<param-value>gb2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping></web-app>
3,包含配置
在开发一个项目时,一般采用模板开发的方式,即一个项目由多个模块组成,每个模块由某个项目或者某些程序员来开发,每个程序员都可以创建使用自己的配置文件,然后把模块集成在一起。
在struts.xml中文件包含的格式如下:
<span style="font-size:24px;"> <!-- 倒入一个配置文件,通过这种方式可以将struts2的Action按模板配置到多个配置文件中 -->
<include file="别的配置文件"></include></span>
<include>的属性是file:指定文件名
例如:
<include file="struts-view.xml"></include>
<include file="struts-edit.xml"></include>
<include file="struts-help.xml"></include>
<include file="struts-eventing.xml"></include>