實現一個簡單的計算器程序,要求:使用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中完成的,實際的項目中,業務不會這麼簡單,常常涉及到一些對數據庫的操作,應該把各個成分都給分離開來,這樣以後維護起來也容易多了,也會讓程序員賞心悅目,假如是一個邏輯層次劃分的不是很良好的項目,維護起來真叫人惡心,讓我抓狂。