两个页面,一个输入页面,接收值,另一个页面打出计算后的值
知识点:</p>
1:如何接收jsp页面的数据,并处理。
2:jsp中如何使用java 片段
3:jsp中如何调用javaScript完成对数据合法性的校验
第一个JSP页面myCal01.jsp
<!-- 这是计算器的界面 --> <%@page contentType="text/html;charset=gb2312" %> <html> <h1>我的计算器</h1> <hr> <head> <!--在jsp中添加javaScript代码,防止用户空提交--> <!--在sumbit控件上添加οnclick="checkNum" 即可触发调用这个函数,注意是函数名后面要加括号--> <!--但仅仅触发js函数的话,页面仍然跳转,阻止跳转的方式是 在函数名和括号前加return 返回false的话表达不跳转--> <script language="javascript"> <!-- //写一个函数证明用户是不是空提交 function checkNum(){ //判断是不是空 if(form01.num1.value == ""){ window.alert("第一个数不能为空"); return false; } if(form01.num2.value == ""){ window.alert("第二个数不能为空"); return false; } //判断是不是数 if(Math.round(form01.num1.value) != form01.num1.value){ window.alert("第一个数必须是数字"); return false; } if(Math.round(form01.num2.value) != form01.num2.value){ window.alert("第二个数必须是数字"); return false; } } --> </script> </head> <body> <form name="form01" action="result.jsp"> 请输入第一个数:<input type="text" name="num1"><br> <select name="flag"> <option>+</option> <option>-</option> <option>*</option> <option>/</option> </select> <br> 请输入第二个数:<input type="text" name="num2"><br> <input type="submit" value="计算" οnclick="return checkNum()"/> </form> <hr> </body> </html>
第二个JSP页面result.jsp
<!-- 得到数据并计算 --> <%@page contentType="text/html;charset=gb2312" %> <html> <h1>我的计算器</h1> <h7>演示页面之间传值,用的是request.getParameter(),在上一个页面Action中放的是这个页面的全名(包括后缀.jsp)</h7> <hr> <body> <% //接收第一个数(根据控件的名字取值) String strNum1 = request.getParameter("num1"); //接受第二个数 String strNum2 = request.getParameter("num2"); //接收符号 String flag = request.getParameter("flag"); char charFlag = flag.charAt(0); int num01 = Integer.parseInt(strNum1); int num02 = Integer.parseInt(strNum2); int result = 0; //计算 switch(charFlag){ case '+':result = num01 + num02; break; case '-':result = num01 - num02; break; case '*':result = num01 * num02; break; case '/':result = num01 / num02; break; } out.println(result); //输出结果 %> </body> </html>