(1)jsp實現網頁計算器代碼如下:只有兩個jsp頁面
myCal.jsp如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>My JSP 'myCal.jsp' starting page <script language="javascript"> </script>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>My JSP 'myResult.jsp' starting page <% //第1步接收到 第1個數 String s_num1 = request.getParameter("num1"); //第2步接收到 第2個數 String s_num2 = request.getParameter("num2"); //第3步接收到 運算符 String flag = request.getParameter("flag"); //第4步 計算 int num1 = Integer.parseInt(s_num1); int num2 = Integer.parseInt(s_num2); int result = 0; if(flag.equals("+")) { result = num1+num2; } else if(flag.equals("-")) { result = num1-num2; } else if(flag.equals("*")) { result = num1*num2; } else if(flag.equals("/")) { result = num1/num2; } //第5步 out.println("結果是:"+result); %>
(2)雖然過程很簡單但是有幾個值得學習的地方:
如何判斷輸入的數據是不是數字:使用Math.round(form1.num1.value) != form1.num1.value 來判斷;
如何獲取操作值:設置name屬性 flag實現;