LookupDispatchAction是用來解決一個表單多個送出的情況。下面通過一個簡單的運算器執行個體,來介紹下它的使用。
1.配置檔案(這是為了實作國際化的功能,本例隻實作了中文和英文國際化):
AppResources.properties :
btn.add=add
btn.subtract=subtract
AppResources_zh.properties:(要使用Native2ASCII轉化,本例為了友善就使用漢語拼音代替了)
btn.add=jia
btn.subtract=jian
2.輸入頁面:submit.jsp
<bean:define id="add">
<bean:message key="btn.add"/>
</bean:define>
<bean:define id="sub">
<bean:message key="btn.subtract"/>
</bean:define>
<form action="/strutsapp/math.do" method="GET">
Number A :<input type="text" name="a"/><br/>
Number B :<input type="text" name="b"/><br/>
<input type="submit" name="btn" value="${add}"/>
<input type="submit" name="btn" value="${sub}"/>
</form>
3.配置檔案:struts-config.xml
<form-beans>
<form-bean name="allForm" type="org.apache.struts.action.DynaActionForm">
<form-property name="a" type="java.lang.Integer"/>
<form-property name="b" type="java.lang.Integer"/>
</form-bean>
</form-beans>
<action-mappings>
<action parameter="btn" path="/math" type="com.kettas.struts.MathAction" name="allForm">
<forward name="ok" path="/ret.jsp"/>
</action>
</action-mappings>
4.Action類: MathAction.java
public class MathAction extends LookupDispatchAction{
@Override
public Map getKeyMethodMap(){
//按鈕的值應來自于資源檔案.
//在map中儲存是資源檔案中的key
Map m = new HashMap();
m.put( "btn.add" , "addOperate" );
m.put( "btn.subtract" , "subOperate" );
return m ;
}
public ActionForward addOperate( ActionMapping mapping,
ActionForm form ,
HttpServletRequest request ,
HttpServletResponse response){
DynaActionForm daf = (DynaActionForm)form ;
Integer a = (Integer)daf.get( "a" ) ;
Integer b = (Integer)daf.get( "b" ) ;
int ret = a.intValue() + b.intValue();
request.setAttribute( "ret" , ret ) ;
return mapping.findForward( "ok" ) ;
public ActionForward subOperate( ActionMapping mapping,
ActionForm form ,
HttpServletRequest request ,
HttpServletResponse response){
DynaActionForm daf = (DynaActionForm)form ;
int ret = a.intValue() - b.intValue();
}
5.結果頁面: ret.jsp
<c:if test="${!empty ret}">
<h2>ret= ${ret}</h2>
<c:if>
本文轉自NightWolves 51CTO部落格,原文連結:http://blog.51cto.com/yangfei520/230886,如需轉載請自行聯系原作者