這篇博客介紹,學習struts中的模式匹配。
以對用戶的操作講,包括四種操作:增、刪、改、查,開發中,如果每一種操作都對應一個action,那麼開發一個項目中,每種邏輯都按這樣開發,那麼每個邏輯都應四個action類,這樣會有很多的action。沒有必要,爲了簡化,每個邏輯的增、刪、改、查都寫在一個action中。struts1通過模式匹配判斷在一個Action中調用相應的方法。
以管理用戶實例來演示。主要是strus-config.xml文件的配置,不管用戶增、刪、改、查的邏輯處理。
1.管理用戶類:
package com.bjpowernode.struts;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
/**
* 管理用戶類,實現用戶的增、刪、改、查
* @author xj
*
*/
public class UserAction extends DispatchAction {
//添加用戶
public ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)throws Exception {
return mapping.findForward("success");
}
//刪除用戶
public ActionForward del(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)throws Exception {
return mapping.findForward("success");
}
//修改用於
public ActionForward update(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)throws Exception {
return mapping.findForward("success");
}
}
2.配置文件
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
"http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<action-mappings>
<action path="/user/*"
type="com.bjpowernode.struts.UserAction"
parameter="command"
>
<forward name="success"path="/user/{1}_success.jsp"/>
</action>
</action-mappings>
</struts-config>
3.JSP頁面調用
<body>
<a href="user/add.do?command=add">添加</a><br>
<a href="user/del.do?command=del">刪除</a><br>
<a href="user/update.do?command=update">修改</a><br>
</body>
總結:
在配置文件中,<action-mappings>
中<action>
標籤的路徑配置,使用通配符。不論用戶請求哪些頁面,都會讀取此<action>
的配置。截取用戶請求連接,映射到userAction中,根據parameter的配置,調用相應的方法,完成邏輯處理,進行頁面跳轉。
在配置文件中,跳轉路徑存在一個佔位符,這個佔位符,將是從截取用戶訪問連接中截取。所以,這裏存在一個約定,用戶請求的路徑中的名稱必須與將要跳轉到的頁面名稱一致。
在這個實例中,以添加爲例,請求連接爲“/user/add.do”,所以,會存在add_success.jsp頁面.作爲用戶添加用戶成功後,將要跳轉到的頁面。