关闭

JSP学习笔记---应用做个简易计算器JSP+javabean

标签: javabeanjspjavabean+jsp应用简易计算器
135人阅读 评论(0) 收藏 举报
分类:

注意:

1.用到了<jsp:setProperty  property="*"  name="calculate"/>标签,注意javabean中参数变量务必要与表单提交数据名称相同。


Main.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'Main.jsp' starting page</title>
  </head>
  
  <body>
  
  <jsp:useBean id="calculate"   class="com.wanhao.Calculate"/>
  <jsp:setProperty property="*" name="calculate"/>
<%
     calculate.calculate();
     out.write(calculate.getFirstNum()+calculate.getOperator()+calculate.getSecondNum()+"="+calculate.getResult());
 %>

 <form  action="/Calculate/Main.jsp"  method="post">
输入第一个数:<input type="text" name="firstNum">
选择操作:
<select name="operator">
      <option>+
      <option>-
      <option>*
      <option>/
</select>
输入第二个数:<input type="text" name="secondNum">
<input type="submit" name="计算"   >
</form> 

  </body>
</html>
Calculate.java

package com.wanhao;

import java.math.BigDecimal;

public class Calculate {
    String firstNum="0";
    char operator='+';
    String secondNum="0";
    String result="0";
	public char getOperator() {
		return operator;
	}
	public void setOperator(char operator) {
		this.operator = operator;
	}
	public String getResult() {
		return result;
	}
	public void setResult(String result) {
		this.result = result;
	}
	public String getFirstNum() {
		return firstNum;
	}
	public void setFirstNum(String firstNum) {
		this.firstNum = firstNum;
	}
	public String getSecondNum() {
		return secondNum;
	}
	public void setSecondNum(String secondNum) {
		this.secondNum = secondNum;
	}
	public void calculate()
	{
		BigDecimal  number1=new BigDecimal(firstNum);
		BigDecimal number2=new BigDecimal(secondNum);
         switch(operator)
         {
         case '+':  result=number1.add(number2).toString();break;
         case '-':   result=number1.subtract(number2).toString();break;
         case '*':   result=number1.multiply(number2).toString();break;
         case '/':   result=number1.divide(number2, 10, BigDecimal.ROUND_UP).toString();break;
         default:  result="0";
         }
		
	}
    
}





0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:131080次
    • 积分:4497
    • 等级:
    • 排名:第6584名
    • 原创:334篇
    • 转载:19篇
    • 译文:0篇
    • 评论:15条
    博客专栏
    最新评论