Struts1.x教程:配置文件总结
要想使用Struts,至少要依靠两个配置文件:web.xml和struts-config.xml。其中web.xml用来安装Struts框架。而struts-config.xml用来配置在Struts框架中要使用的资源。如Formbean、Action、插件等。如果使用了某些插件,如Validator、Tiles等。还可能需要其他的配置文件。
看到一篇关于struts1.x总结,推荐给大家
(http://blog.csdn.net/ibone/archive/2009/06/26/4299559.aspx)
一、在web.xml中安装Struts
要想使用Struts,我们接触到的第一个配置文件就是web.xml。实际上,Struts的入口点是一个名为ActionServlet的Servlet。在第一次访问Struts时,建立这个ActionServlet类的对象实例,并调用ActionServlet类中的init方法来进行初始化(其实是读取struts-config.xml文件中的内容,并根据struts-config.xml中的内容来初始化相关的资源)。因此,就要在web.xml文件中安装这个ActionServlet,并在ActionServlet的初始化参数中指定struts-config.xml的位置。
二、struts-config.xml文件的结构
struts-config.xml是Struts的核心配置文件。也就是说,只要是使用Struts,就必须配置struts-config.xml文件。struts-config.xml文件的所有配置项都要放到顶层元素<struts-config>中,主要配置项有如下七个:
1. FormBean:在<form-beans>元素中配置。
2. Action映射:在<action-mappings>元素中配置。
3. 全局Forwards:在<global-forwards>元素中配置。
4. 全局异常(Exception):在<global-exceptions>元素中的配置。
5. 控制器(Controller):在<controller>元素中配置。
6. 信息资源:在<message-resources>元素中的配置。
7. 插件:在<plug-in>元素中配置。
下面我们就分别来看一下这七部分的具体配置方法。
三、配置Formbean和Action映射
这两个配置项是Struts配置的核心,也就是说我,一个完整的Struts应用程序都会拥有这两项配置。
每一个Formbean要在<form-beans>元素中定义一个<form-bean>子元素。下面的代码给出了一个标准的Formbean的配置方法:
<form-beans> <form-bean name="myForm" type="actionform.MyActionForm" /></form-beans>
<action-mappings> <action name="myForm" path="/myaction" scope="request" validate="true" type="action.MyAction" input="/mystruts/error.jsp"> <forward name="success" path=" /mystruts/success.jsp" /> </action></action-mappings>
<global-forwards> <forward name="myforward" path="/mystruts/newProduct.jsp" /></global-forwards>
<global-exceptions > <exception key="error.name.blank" type="java.lang.Exception" path="/error.jsp"/></global-exceptions>
<global-exceptions> <exception key="error.email. invalid" type="java.lang.Exception" handler="exceptions.EmailException"/></global-exceptions>
public ActionForward execute( Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance, HttpServletRequest request, HttpServletResponse response) throws ServletException ;
<controller maxFileSize="2M" contentType = “text/html” nocache = “false” />
<message-resources parameter="struts.application" key="global" />其中parameter属性表示保存信息资源的属性文件的位置,对于上面的代码来说,属性文件的位置是<Web根目录>"WEB-INF"classes"struts"application.properties。key属性表示application.properties文件的标识。如果没有key属性,这个属性文件就是默认的属性文件。当指定key属性时,在使用这个属性文件时,需要使用相关标签的bundle属性指定这个key值。
<bean:message key="key.msg.submit" bundle=”global”/>
errors.add("name",new ActionMessage("error.name.blank")); 而在JSP页面中可以使用如下的代码来显示这个错误信息:<plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml, /WEB-INF/validator.xml" /></plug-in>