JAVA web 设计 计算器

  1. 实验目的

掌握怎样在JSP中使用request对象获取form表单提交的text(文本框)以及以下select(下拉列表)中的数据。掌握使用request对象实现重定向。

  1. 实验要求

(1)编写input.jsp,该页面提供一个form表单,该form表单体中两个text文本框,用于用户输入数字,提供一个select下拉列表,该下拉列表有加减乘除四种运算,供用户选择运算。用户在form表单中输入的数字,选择运算符号,单机submit提交键将这些数据提交给computer.jsp页面。

(2)computer.jsp页面获取input.jsp提交的数据,计算出相应的结果显示给用户。如果computer.jsp页面没有获取到数据。就将用户重新定向到input页面。

(3)在Tomcat服务器的Webapps目录下(例如:,D://apache-tomcat-9.0.26\webapps)新建名称是ch4_practice_two的Web服务目录下。把JSP页面都保存到该目录中。

(4)用浏览器访问input.jsp页面。

  1. 参考代码

input.jsp
<%@ page contentType="text/html" %>
<%@ page pageEncoding = "utf-8" %> 
<HTML><body bgcolor = #ffccff>
<form action="computer.jsp" method=post name=form>
<p style="font-family:宋体;font-size:18;color:blue">
输入运算数、选择运算符号:<br>
  <input type=text name="numberOne" size=6/>
       <select name="operator" >
          <option selected="selected" value="+">加
          <option value="-">减
          <option value="*">乘
          <option value="/">除
       </select> 
  <input type=text name="numberTwo"  size=6 />
  <br><input type="submit" name="submit" value="提交" />
</form> 
</p></body></HTML>
computer.jsp
<%@ page contentType="text/html" %>
<%@ page pageEncoding = "utf-8" %> 
<HTML><body bgcolor = cyan>
<p style="font-family:宋体;font-size:18;color:black">
<% 
   String numberOne=request.getParameter("numberOne");
   String numberTwo=request.getParameter("numberTwo");
   String operator=request.getParameter("operator");
   if(numberOne==null||numberOne.length()==0) {
        response.sendRedirect("input.jsp"); 
        return;
   }
   else if(numberTwo==null||numberTwo.length()==0) {
        response.sendRedirect("input.jsp"); 
        return;
   }
   try{
        double a=Double.parseDouble(numberOne);
        double b=Double.parseDouble(numberTwo);
        double r=0;
        if(operator.equals("+"))
           r=a+b;
        else if(operator.equals("-"))
           r=a-b;
        else if(operator.equals("*"))
           r=a*b;
        else if(operator.equals("/"))
           r=a/b;
        out.print(a+""+operator+""+b+"="+r);
    }
    catch(Exception e){
        out.println("请输入数字字符");
    }
%>
</body></HTML>

运行结果该处就展示了两种运算,四种运算都是可以实现的。

  • 4
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值