LookupDispathcAction主要用于一个表单有多个按钮,而这写表单又有相同的name属性时,使用。
1、定义ExtendLookupDispatchAction类
package com.sunrex.demo08.action; import java.util.HashMap; import java.util.Map; 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.LookupDispatchAction; public class ExtendLookupDispatchAction extends LookupDispatchAction { public ActionForward addItem(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward("addItem"); } public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward("list"); } @Override protected Map<String, String> getKeyMethodMap() { Map<String, String> maps = new HashMap<String, String>(); maps.put("submit.addItem", "addItem"); maps.put("submit.list", "list"); return maps; } }
2、定义ApplicationMessages.properties文件
submit.addItem=addItem submit.list=list
3、配置struts-config.xml文件
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd"> <struts-config> <action-mappings> <action path="/lookup" type="com.sunrex.demo08.action.ExtendLookupDispatchAction" scope="request" parameter="method" > <forward name="addItem" path="/demo08/addItem.jsp"/> <forward name="list" path="/demo08/list.jsp"/> </action> </action-mappings> <message-resources key="demo08" parameter="com.sunrex.demo08.ApplicationMessages"/> </struts-config>
4、定义index.jsp页面
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=GB18030"> <title>Insert title here</title> </head> <body> <form action="../lookup.do" method="post"> 名:<input type="text" name="username"><br> <input type="submit" name="method" value="addItem"> <input type="submit" name="method" value="list"> </form> </body> </html>
注意以上jsp文件中的两个按钮的name为method,他与struts-config.xml中action标签下的parameter的值对应
点击addItem按钮,就访问ExtendLookupDispatchAction类中的addItem方法,而list会使用ExtendLookupDispatchAction中的list方法