执行简单的算术运算,并在同一个jsp页面上显示结果



我试着把我的头绕在servlet和JSP上,当我实现一个简单的计算器时,我卡住了。

基本上,我有两个输入字段,操作员选择字段和提交按钮。

当我单击提交按钮时,我需要对输入元素中的两个值执行所选的算术运算,并在同一页面上显示结果。

我有:

<!-- hello.jsp page -->
<form action="hello.jsp" id="calc-form">
    <input type="number" name="num1" required>
    <select id="opers" name="oper">
        <option>+</option>
        <option>-</option>
        <option>*</option>
        <option>/</option>
    </select>
    <input type="number" name="num2" required>
    <input type="submit" value="Calculate">
</form>
<h2>The result is: ${result}</h2>

my doGet method in hello servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    System.out.println("Hello#doGet");
    String strNum1 = request.getParameter("num1");
    String strNum2 = request.getParameter("num2");
    String oper = request.getParameter("oper");
    double a, b, result = 0;
    if(validateNum(strNum1) && validateNum(strNum2) && validateOper(oper)) {
        try {           
            a = Double.parseDouble(request.getParameter("num1"));
            b = Double.parseDouble(request.getParameter("num2"));
            switch(oper) {
            case "+":
                result = a + b;
                break;
            case "-":
                result = a - b;
                break;
            case "*":
                result = a * b;
                break;
            case "/":
                if (b == 0) {
                    throw new ArithmeticException("Division by zero is not allowed");
                } else {
                    result = a / b;
                }
            }
        } catch(NumberFormatException | ArithmeticException e) {
            // handle the exception somehow
        }
        request.setAttribute("result", result);
    }
    RequestDispatcher dispatcher = request.getRequestDispatcher("/hello.jsp");
    dispatcher.forward(request, response);
}

所以,当我进入http://localhost:8080/test2/hello,在输入元素中输入数字并按提交时,我被重定向到看起来很像这样的地址:http://localhost:8080/test2/hello.jsp?num1=4&oper=*&num2=4

但是,我没有得到结果。

你能告诉我我哪里做错了吗?

看看你的动作

   <form action="hello.jsp" id="calc-form">

您需要将您的操作指向servlet。而不是JSP。

最新更新