1. 程式人生 > >Struts1應用、實現簡單計算器、使用DispatchAction、顯示友好的報錯信息、使用動態Form簡化開發

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

實體類 ica setattr sources 建立 -s number asc rlogin

實現簡單的支持加、減、乘、除的計算器

復制一份Struts1Demo改動:Struts1Calc

方案1: Struts1Calc

創建ActionForm:
CalcForm extends ActionForm。 num1 num2。生成getter setter;

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

AddAction:

public class AddAction extends Action {
	@Override
	public 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 {
	@Override
	public 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。系統規模變大時,easy混亂

方案2將相關操作組織在一個Action中,通過operate參數區分不同操作,但easy使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;
		else
			return 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

源代碼 http://pan.baidu.com/s/1eQcOx38

顯示友好的報錯信息另外一種方式

加入到全局錯誤信息中,作用域是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. easy漏改出錯 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 中對應代碼

easy漏掉某處而引入錯誤

使用實體對象作為Form屬性

我們已經知道:
頁面提交的表單數據,能夠自己主動填充到ActionForm中


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


假如。頁面代碼是這種:
<input name="user.uname" />


表單域的值是否可以自己主動填充到Form中呢?

復制一份Struts1Demo,改動為Struts1Login

ActionForm代碼

public class LoginForm extends ActionForm {
	private User user = new User();
	private String rePassword;

struts-config.xml

<struts-config>
	<!-- Form -->
	<form-beans>
		<form-bean name="userLoginForm" type="com.demo.form.LoginForm"></form-bean>
	</form-beans>

	<!-- Action -->
	<action-mappings>
		<action name="userLoginForm" path="/login" type="com.demo.action.LoginAction"
			scope="request">
			<forward name="success" path="/success.jsp"></forward>
			<forward name="input" path="/index.jsp"></forward>
		</action>
	</action-mappings>
</struts-config>


Action代碼


if (userBiz.login(lf.getUser())) { ...


避免了“純體力”型編碼, 數據庫字段增減時。無需改動Form和Action代碼

源代碼:http://pan.baidu.com/s/1sjucV85

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