jsp计算器V2.0

<%@ 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 'AllCal.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="js/js1.js"></script>
  </head>
  <%
  	String num1 = "0";
  	num1 = request.getParameter("num1"); //通过属性name还是属性id获取?
  	String num2 = "0";
  	num2 = request.getParameter("num2");
  	/**
  		空提交,肯定会报错,用js来验证合法性
  	 */
  	String op = request.getParameter("operator");
  	double result = 0;
  	double d_num1 = 0;
  	double d_num2 = 0;
  	//判断接受到的数据不为空,为空的话,无法转换
	//打开此页面之前,num1/num2 都会接受一个空值 , Double.parseDouble(null) 会报错
	//所以先判断,打开的时候,为空,但是我们不去做转换,就不报错,弹出输入界面,输入数据之后,判断非空了,才转换
	//两个页面的情况下,第一个页面直接是输入页面,通过action="jsp1/jsp1.jsp" 跳转过去,不存在空值问题
  	if(num1!= null&&num2 != null&&op!= null ){
  		 d_num1 = Double.parseDouble(num1);
  		 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;
  	}
  %>
  
  <body>
    <form action="/jsp1/AllCal.jsp" method="post">
			<%--
    	method="post" 和  method="get"的区别 
    	
    --%>
			第一个运算数:
			<input type="text" id="id1" value="<%=num1 %>" name="num1" />
			<br />
			第二个运算数:
			<input type="text" id="id2" value="<%=num2 %>" 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" onclick="return checkNum()" value="计算" />
			<%--onclick="return checkNum()" 等价于 
		 <form action="??"onsubmit="return checkNum()" method="post">--%>
		</form>
		<hr color="00ffff">
		运算结果:<%=result%>
  </body>
</html>

 

你可能感兴趣的:(jsp)