jsp+javaBean 计算器实例
package com.wzh.test.domain; import java.math.BigDecimal; public class CalculatorBean { private String firstNumber="0"; private char operator; private String secondNumber="0"; private String result; public String getFirstNumber() { return firstNumber; } public void setFirstNumber(String firstNumber) { this.firstNumber = firstNumber; } public char getOperator() { return operator; } public void setOperator(char operator) { this.operator = operator; } public String getSecondNumber() { return secondNumber; } public void setSecondNumber(String secondNumber) { this.secondNumber = secondNumber; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public void calculate() { BigDecimal firstBigDecimal = new BigDecimal(this.firstNumber); BigDecimal secondBigDecimal = new BigDecimal(this.secondNumber); switch (this.operator) { case '+': this.result = firstBigDecimal.add(secondBigDecimal).toString(); break; case '-': this.result = firstBigDecimal.subtract(secondBigDecimal).toString(); break; case '*': this.result = firstBigDecimal.multiply(secondBigDecimal).toString(); break; case '/': this.result = firstBigDecimal.divide(secondBigDecimal).toString(); break; default: break; } } }
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Calculator.jsp' starting page</title> </head> <body> <jsp:useBean id="calculator" class="com.wzh.test.domain.CalculatorBean"></jsp:useBean> <jsp:setProperty property="*" name="calculator"/> <% calculator.calculate(); %> <jsp:getProperty property="firstNumber" name="calculator"/> <jsp:getProperty property="operator" name="calculator"/> <jsp:getProperty property="secondNumber" name="calculator"/> = <jsp:getProperty property="result" name="calculator"/> <form action="/day09/calculator.jsp" method="post"> <table> <tr> <td>第一个数:</td> <td><input type="text" name="firstNumber"/> </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="secondNumber"/></td> </tr> <tr> <td><input type="submit"/> 结果:</td> <td><span id="result"><%=calculator.getResult() %></span></td> </tr> </table> </form> </body> </html>