首页 > 技术文章 > Jsp版本的计算器(九大对象)

helloworld2019 2019-06-14 17:18 原文

只在本页面生效

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>

<body>
<%
pageContext.setAttribute("abc", "shunping");
%>
<%
String val=(String)pageContext.getAttribute("abc");
out.print(val);
%>>
</body>
</html>
View Code

eg:计算器

caculator.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="result.jsp" method="post">
请输入第一个数:<input type="text" name="num1"/><br/>
请输入第二个数:<input type="text" name="num2"/><br/>
请选择运算符号:<select name="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br/>
<input type="submit" value="计算"/>
</form>
</body>
</html>
View Code

result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String num1=request.getParameter("num1");
String num2=request.getParameter("num2");
String operator=request.getParameter("operator");
double d_num1=Double.parseDouble(num1);
double d_num2=Double.parseDouble(num2);
double res=0;
if(operator.equals("+")){
res=d_num1+d_num2;
}else if(operator.equals("-")){
    res=d_num1-d_num2;    
}else if(operator.equals("*")){
    res=d_num1*d_num2;
}else{
    res=d_num1/d_num2;
}
out.print("结果是"+res);
%>
</body>
</html>
View Code

 处理输入空值或者字母等还未考虑,日后再说

推荐阅读