Struts1應用、實現簡單計算機、使用DispatchAction、顯示友好的報錯資訊、使用動態Form簡化開發

來源:互聯網
上載者:User

標籤:style   class   blog   code   java   http   

實現簡單的支援加、減、乘、除的計算機複製一份Struts1Demo修改:Struts1Calc
方案1: Struts1Calc建立ActionForm:
CalcForm extends ActionForm, num1 num2,產生getter setter;

建立4個Action,在頁面中,通過JavaScript控制提交到不同的Action Bean。

AddAction:

public class AddAction extends Action {@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {CalcForm cf = (CalcForm) form;int result  = cf.getNum1()+cf.getNum2();request.setAttribute("result", result);return mapping.findForward("success");}}

其他三個省略。。

在wen.xml的servlet
添加
    <load-on-startup>1</load-on-startup>


struts-config.xml裡面的配置:

<!-- Form --><form-beans><form-bean name="calcForm" type="com.demo.form.CalcForm"></form-bean></form-beans><!-- Action --><action-mappings><action name="calcForm" path="/add" type="com.demo.action.AddAction"scope="request"><forward name="success" path="/result.jsp"></forward><forward name="input" path="/calc.jsp"></forward></action></action-mappings>


其他三個配置省略…

 
添加clac.jsp

  </head>  <script type="text/javascript">  function calc(c){  document.getElementById("form").action=c+".do";  document.getElementById("form").submit();  }  </script>  <body>  <form id="form" action="#" method="post">  第一個數:<input name="num1"><br/>  第二個數:<input name="num2"><br/>  <input type="button" value="加" onclick="calc('add')">  <input type="button" value="減" onclick="calc('sub')">  <input type="button" value="乘" onclick="calc('mul')">  <input type="button" value="除" onclick="calc('div')">  </form>  </body>

添加result.jsp

第一個數:${requestScope.calcForm.num1 }
<br /> 第二個數:${requestScope.calcForm.num2 }
<br /> 結構:${requestScope.result}

部署訪問:

http://localhost:8080/Struts1Calc/calc.jsp

源碼下載

http://pan.baidu.com/s/1kTDRVi3

方案2:

增加隱藏表單域,表示操作類型 ,在Action Bean中根據不同操作類型做不同處理。
在calc.jsp表單添加: 

    <input id="oper" name="oper" type="hidden"value="oper">

指令碼修改為: 

 <script type="text/javascript">  function calc(c){  /* document.getElementById("form").action=c+".do"; */  document.getElementById("oper").value=c;  document.getElementById("form").submit();  }  </script>

將form的action修改為action="calc.do"

struts-config.xml裡面的<action-mappings>的calcForm的path修改為calc 配置:

<action name="calcForm" path="/calc" type="com.demo.action.CalcAction" scope="request"><forward name="success" path="/result.jsp"></forward><forward name="input" path="/calc.jsp"></forward></action>

在CalcForm添加

private String oper;
和getter和setter方法;
修改CalcAction
public class CalcAction extends Action {@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {CalcForm cf = (CalcForm) form;int result = 0;if("add".equals(cf.getOper())){result  = cf.getNum1()+cf.getNum2();}else if("div".equals(cf.getOper())){result = cf.getNum1()/cf.getNum2();}//....request.setAttribute("result", result);return mapping.findForward("success");}}
部署訪問:
http://localhost:8080/Struts1Calc2/calc.jsp 測試加和除;

源碼:http://pan.baidu.com/s/1c0nbPsc

使用DispatchAction

以上兩個方案說明:

方案1對每個操作都建立一個Action,系統規模變大時,容易混亂

方案2將相關操作組織在一個Action中,通過operate參數區分不同操作,但容易使Action中execute方法的代碼過長,不易維護

使用DispatchAction實現電腦器的步驟:

複製上一個項目Struts1Calc2修改為:Struts1CalcDispatchAction

1. 建立CalcAction,繼承自DispatchAction

2. 在CalcAction中建立加、減、乘、除四個方法

打ex 按alt+/  選擇參數HttpServletResponse ... 然後將方法名改為add、div...

public ActionForward add(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {CalcForm cf = (CalcForm) form;int result = 0;result = cf.getNum1() + cf.getNum2();request.setAttribute("result", result);return mapping.findForward("success");}/*public ActionForward div  … public ActionForward sun   … public ActionForward mul   … */

在struts-config.xml中配置CalcAction

在action-mapping裡  parameter="oper"

<action name="calcForm" path="/calc" type="com.demo.action.CalcAction"scope="request" parameter="oper"><forward name="success" path="/result.jsp"></forward><forward name="input" path="/calc.jsp"></forward></action>
Parameter裡有oper, calc.jsp裡面也要有對應

<input id="oper" name="oper" type="hidden" value="oper">



3. 編寫頁面代碼
不修改頁面;

Dispatch的運行原理
DispatchAction能夠根據傳入參數值自動選擇Action中同名的方法執行


Parameter有點類似我們Struts2的method;


部署運行:
http://localhost:8080/Struts1CalcDispatchAction1/calc.jsp

源碼:http://pan.baidu.com/s/1bnnJOIV

顯示友好的報錯資訊

Struts提供了報錯機制,用於提供友好的報錯資訊給使用者
被除數為0,非數字等

建立屬性檔案 ApplicationResources.properties 在com.demo.resources下


通過在屬性檔案中定義errors.header和errors.footer屬性設定錯誤資訊格式

修改設定檔 struts-config

<message-resources parameter="com.demo.resources.ApplicationResources"></message-resources>
修改對應Action方法

輸入的時候不是數字 和被除數是零的時候 ,這裡只做div除

public ActionForward div(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {CalcForm cf = (CalcForm) form;ActionMessages errors = new ActionMessages();if (!this.isFloat(cf.getNum1())) {errors.add("error1",new ActionMessage("error.valudate.inputnumber"));}if (this.isZero(cf.getNum2())) {errors.add("error2", new ActionMessage("error.valudate.number"));}if (!errors.isEmpty()) {super.saveErrors(request, errors);return mapping.findForward("input");}int result = 0;result = cf.getNum1() / cf.getNum2();request.setAttribute("result", result);return mapping.findForward("success");}private boolean isZero(int num2) {return num2 == 0;}private boolean isFloat(int i) {if (i==0)return false;elsereturn true;}

在頁面上顯示報錯資訊

<%@ taglib prefix="html" uri="http://struts.apache.org/tags-html" %>  第一個數:<input name="num1"><html:errors property="error1" /><br/>  第二個數:<input name="num2"><html:errors property="error2" /><br/>

部署運行 被除數輸入0 測試;http://localhost:8080/Struts1CalcDispatchAction1/calc.jsp

源碼 顯示友好的報錯資訊第二種方式

添加到全域錯誤資訊中,範圍是request

if (!this.isFloat(cf.getNum1())) {errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.valudate.inputnumber"));// errors.add("error1",new// ActionMessage("error.valudate.inputnumber"));}if (this.isZero(cf.getNum2())) {// errors.add("error2", new ActionMessage("error.valudate.number"));errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.valudate.number"));}

vlac.jap 裡使用 <html:errors /> 顯示所有錯誤資訊;


使用動態Form簡化開發使用Struts架構開發時,對每一個頁面提交的屬性都要建立一個ActionForm屬性
回顧計算機的ActionForm屬性
1. 只有兩個屬性2. 如果處理複雜的業務時,屬性可能會非常的多3. 容易漏改出錯4. 大量的“純體力”代碼充斥其中

解決問題 使用動態Form

以配置的方式建立Form  struts-config.xml:

<form-beans><form-bean name="calcDynaForm" type="org.apache.struts.action.DynaActionForm"><form-property name="num1" type="java.lang.Integer" /><form-property name="num2" type="java.lang.Integer" /></form-bean></form-beans>

和使用普通Form一樣

<action name="calcDynaForm" parameter="oper" path="/calc"scope="request" type="com.demo.action.CalcAction"><forward name="success" path="/result.jsp"></forward><forward name="input" path="/calc.jsp"></forward></action>

Action代碼

    ……

 DynaActionForm cf =(DynaActionForm) form;

……

   result =(Integer)cf.get("num1")/(Integer)cf.get("num2");  

……


使用實體物件作為Form屬性  使用動態ActionForm的好處

  省去了編寫ActionForm類

  頁面提交資料變化時只須修改struts-config.xml中的配置

  使用動態ActionForm的缺陷

  Action中的代碼並沒有因此變得簡單

  商務邏輯變化、資料庫增減欄位時,需要修改的地方包括實體類、動態ActionForm定義和Action 中相應代碼

  容易漏掉某處而引入錯誤

使用實體物件作為Form屬性

我們已經知道:
頁面提交的表單資料,可以自動填滿到ActionForm中


假如,ActionForm的代碼是這樣的:
public class UserForm 
extends ActionForm {
    private USER user = new USER();
    // getter and setter
}


假如,頁面代碼是這樣的:
<input name="user.uname" />


表單域的值是否能夠自動填滿到Form中呢?

ActionForm代碼


public class UserForm extends ActionForm {
    private USER user = new USER();
    // getter and setter
}


struts-config.xml


<form-bean name="userForm" type="com.aptech.jb.web.form.UserForm" />
     ... 
<action name="userForm" ...


Action代碼


UserForm myForm = (UserForm)form;
// 執行登入
USER userWithUid = userBiz.login( myForm.getUser() );


避免了“純體力”型編碼, 資料庫欄位增減時,無需修改Form和Action代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.