struts-config.xml 文件包含了ActionServlet 需要用來處理對應用請求的詳細信息。爲了練習,我們創建一個空殼的struts-config.xml 文件。
文件存儲在<BaseDirectory>/webapps/register/WEB-INF/目錄下,需要改變的是:
首先,添加/register 到<action>元素的 path 屬性。ActionServlet 使用Web容器轉發給它的URI來選擇正確的Action 類。URI 和ActionMapping 的path 屬性匹配。這裏,請求給出的路徑必須在去除前綴和後綴後和/register 匹配。前綴或後綴通常是/do/ 或者 .do。 我們的練習中,將後綴設置爲.do。當URI 具有一個.do 擴展名,容器就知道將請求轉發給ActionServlet。Struts會自動去除 擴展名,所以我們在配置時不必加上它們。
下一步添加:registerForm 到<action> 元素的 name 屬性。<action> 元素使用name 屬性來識別哪個ActionForm 將被創建,並將提交的表單組裝給他。
然後,添加 app.RegisterAction 到<action> 元素的 type 屬性。ActionServlet 使用這個屬性來識別將用來處理請求的Action 類。
接下來,在<forward> 元素下,添加 success 到 name 屬性,並且 /success.html 到 path 屬性。最後,再在另一個<forward>下添加 failure 到 name 屬性, /failure.html 到 path 屬性。 這些元素將創建ActionForward 對象,我們將用它來選擇程序的控制流。<forward> 元素定義了在RegisterAction中使用的邏輯名稱之間的關聯。
Struts-config.xml 源代碼:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.0//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">
<struts-config>
<form-beans>
<form-bean name="registerForm" type="app.RegisterForm" />
</form-beans>
<action-mappings>
<action path="/register" type="app.RegisterAction"
name="registerForm">
<forward name="success" path="/success.html" />
<forward name="failure" path="/failure.html" />
</action>
</action-mappings>
</struts-config>
Struts框架將struts-config.xml 文件視爲部署描述符使用。它使我們可以創建和改變ActionMapping 和路徑的關聯而不用重新編譯java類。我們也可以改變頁面之間的連接,而不改變JSP模板。
步驟4 創建success.html, failure.html, 以及register.jsp 頁面存放在<Base Directory>/webapps/register目錄下。
success.html
<HTML>
<HEAD>
<TITLE>成功</TITLE>
</HEAD>
<BODY>
恭喜你,註冊成功了
<P>
<A href="register.jsp">繼續註冊嗎?</A>
</P>
</BODY>
</HTML>
failure.html
<HTML>
<HEAD>
<TITLE>對不起</TITLE>
</HEAD>
<BODY>
註冊失敗!
<P>
<A href="register.jsp">還要試一試嗎?</A>
</P>
</BODY>
</HTML>
Register.jsp
<%@ taglib uri="/WEB-INF/struts-form.tld" prefix="form"%>
<form:form action="register.do">
用戶名:<form:text property="username" />
<br>
輸入密碼:<form:password property="password1" />
<br>
再輸一次:<form:password property="password2" />
<br>
<form:submit value="Register" />
</form:form>
整個程序的流程圖如下
現在,試一下運行如何。 如果Tomcat沒有運行,啓動它。
在瀏覽器中輸入以下地址:
http://localhost:8080/register/register.jsp