實現一個簡單的計算機程式,要求:使用jsp+javabean模式實現。
項目原始碼如下:
檔案:calculator.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <%@ page isErrorPage="true"%> <%@ page errorPage="calculator.jsp" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>簡單的電腦</title> </head> <body> <%--建立Calculator對象--%> <jsp:useBean id="cal" class="cn.zq.domain.Calculator" /> <%--設定值 萬用字元*表示設定所有屬性--%> <jsp:setProperty property="*" name="cal"/> <%-- 進行計算 --%> <c:if test="${empty pageContext.exception}"> <% cal.calculate(); %> </c:if> <hr/> <p>計算結果:${cal.firstNum } ${cal.operator } ${cal.secondNum } = ${cal.result }</p> <hr/> <%-- 構建url --%> <c:url var="formUrl" value="/calculator.jsp"/> <form action="${formUrl }" method="post"> <table border="1" cellpadding="2"> <tr> <td colspan="2" align="center">我的計算機</td> </tr> <tr> <td>第一個參數:</td> <td><input type="text" name="firstNum"/></td> </tr> <tr> <td>運算子:</td> <td> <select name="operator"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </select> </td> </tr> <tr> <td>第二個參數:</td> <td> <input type="text" name="secondNum"> </td> </tr> <tr> <td colspan="2"> <input type="submit" value="計算" /> </td> </tr> </table> </form> </body> </html>
本文使用的javabean代碼如下:
package cn.zq.domain; public class Calculator { private String firstNum; private String operator; private String secondNum; private String result; public String getFirstNum() { return firstNum; } public void setFirstNum(String firstNum) { this.firstNum = firstNum; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public String getSecondNum() { return secondNum; } public void setSecondNum(String secondNum) { this.secondNum = secondNum; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public Calculator() {} public Calculator(String firstNum, String operator, String secondNum, String result) { this.firstNum = firstNum; this.operator = operator; this.secondNum = secondNum; this.result = result; } public void calculate(){ if(operator != null && !operator.equals("")){ double first = new Double(firstNum); double second = new Double(secondNum); char oper = operator.charAt(0); switch (oper) { case '+': result = first + second + ""; break; case '-': result = first - second + ""; break; case '*': result = first * second + ""; break; case '/': result = first / second + ""; break; default: throw new RuntimeException("未知運算子!"); } } } }
最終完成的效果圖如下:
總結:前面只是一個小的練習,實際上還是有很多缺陷的,在資料提交後未進行校正。很顯然jsp+javabean模式只適合完成簡單的計算,要是要完成的功能比較複雜的話,這種模式就不合適了。要是在jsp頁面進行一些業務的處理,也使得程式混亂不堪,最後難以維護,上面例子的商務邏輯的處理是直接在javabean中完成的,實際的項目中,業務不會這麼簡單,常常涉及到一些對資料庫的操作,應該把各個成分都給分離開來,這樣以後維護起來也容易多了,也會讓程式員賞心悅目,假如是一個邏輯層次劃分的不是很良好的項目,維護起來真叫人噁心,讓我抓狂。