在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
实现一个简单的计算器程序,要求:使用jsp+javabean模式实现。 <%@ 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> 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中完成的,实际的项目中,业务不会这么简单,常常涉及到一些对数据库的操作,应该把各个成分都给分离开来,这样以后维护起来也容易多了,也会让程序员赏心悦目,假如是一个逻辑层次划分的不是很良好的项目,维护起来真叫人恶心,让我抓狂。 |
请发表评论