【问题标题】:Perform simple arithmetic operation and show the result on the same jsp page执行简单的算术运算并在同一个jsp页面上显示结果
【发布时间】:2016-01-08 10:27:10
【问题描述】:

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

hello servlet 中的我的doGet 方法:

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&amp;oper=*&amp;num2=4

但是,我没有得到结果。

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

【问题讨论】:

    标签: java jsp jakarta-ee servlets


    【解决方案1】:

    看看你的动作

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      相关资源
      最近更新 更多