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

时间:2015-10-10 15:42:55

标签: java jsp java-ee servlets

我试图绕过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>

doGet servlet中的hello方法:

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

但是,我没有得到结果。

请你告诉我我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

看看你的行动

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

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