jsp 计算器界面,后台处理现在也用jsp来处理,后期改用其他来实现
MyCal.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript" src="js/js1.js"></script>
</head>
<body>
<form action="/jsp1/Result.jsp" method="post">
<%--
method="post" 和 method="get"的区别
--%>
第一个运算数:<input type="text" id="id1" name="num1" /><br/>
第二个运算数:<input type="text" id="id2" name="num2" /><br/>
请选择运算符:<select name="operator" id="op">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br>
<input type="submit" οnclick="return checkNum()" value="计算"/>
<%--οnclick="return checkNum()" 等价于
<form action="??"οnsubmit="return checkNum()" method="post">--%>
</form>
</body>
</html>
result.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
</head>
<body>
<%
String num1 = request.getParameter("num1"); //通过属性name还是属性id获取?
String num2 = request.getParameter("num2");
/**
空提交,肯定会报错,用js来验证合法性
*/
String op = request.getParameter("operator");
double result = 0;
double d_num1 = Double.parseDouble(num1);
double d_num2 = Double.parseDouble(num2);
if("+".equals(op)){
result = d_num1+d_num2;
}else if("-".equals(op)){
result = d_num1-d_num2;
}else if("*".equals(op)){
result = d_num1*d_num2;
}else if("/".equals(op)){
result = d_num1/d_num2;
}
out.println("结果是:"+result);
%>
</body>
</html>
js/js1.js
//验证数据的合法性 function checkNum(){ var num1 = document.getElementById("id1").value; //value 不能为Value, 否则报错 var num2 = document.getElementById("id2").value; var op = document.getElementById("op").value; if(num1==""||num2==""){ window.alert("输入不能为空!"); return false; } /*window.alert("测试js!"); return false;*/ //js中正则表达式,来测试输入数据 var reg = /^[1-9]\d*(\.[0-9]+)?$|^0$/i; if(!reg.test(num2)){ //window.alert(num2.construstor); window.alert(num2+" 输入num2不能为字母或其他字符!"); return false } if(!reg.test(num1)){ window.alert("输入num1不能为字母或其他字符!"); return false } //reg = /^[1-9]\d*(\.[0-9]+)?$|^0$/gi; if(num2==0&&op=="/"){ window.alert("除数不能为0"); return false; } }注:
1.当一个jsp网页要注册一个用户,先在客户端用js来对输入的信息做一次验证(格式/是否非空/特殊字符等);
2.代码比较严谨,在服务器这端进行二次验证(控制器servlet/jsp servlet做控制器最合适),用java表达式来再次验证
黑客,可能会修改你的jsp页面,把js验证去掉.导致js验证失效,