使用 JSP/Servlet 和 Ajax 的简单计算器

2022-09-03 00:48:56

这在某种程度上延续了我之前的问题,但我觉得它应该独立存在,特别是因为我得到了非常详细的答案。

我想在JSP中创建一个简单的计算器。将有两个数字文本框和一个添加按钮。理想情况下,我希望答案出现在页面中而不重新加载,但从我得到的答案来看,它似乎对我的规模来说太大了。我可以想到:1)将答案打印到第三个文本框中(这可能吗?)或以某种方式加载带有答案的同一页面(使用添加按钮和全部)(并能够输入不同的数字等等)。

什么是做到这一点的好方法?


答案 1

对于我的体重秤来说,它似乎太大了

这实际上取决于上下文和功能要求。不过,这非常简单和琐碎。这听起来更像是“信息太多”,你实际上需要单独学习单独的概念(HTTP,HTML,CSS,JS,Java,JSP,Servlet,Ajax,JSON等),以便更大的图景(所有这些语言/技术的总和)变得更加明显。你可能会发现这个答案很有用。

无论如何,以下是如何在没有Ajax的情况下仅使用JSP / Servlet来做到这一点:

calculator.jsp:

<form id="calculator" action="calculator" method="post">
    <p>
        <input name="left">
        <input name="right">
        <input type="submit" value="add">
    </p>
    <p>Result: <span id="result">${sum}</span></p>
</form>

与 它一起映射到 的 :CalculatorServleturl-pattern/calculator

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Integer left = Integer.valueOf(request.getParameter("left"));
    Integer right = Integer.valueOf(request.getParameter("right"));
    Integer sum = left + right;

    request.setAttribute("sum", sum); // It'll be available as ${sum}.
    request.getRequestDispatcher("calculator.jsp").forward(request, response); // Redisplay JSP.
}

让Ajaxical的东西工作也不难。这是在JSP的HTML中包含以下JS的问题(请滚动到右侧以查看代码注释,其中解释了每一行的作用):<head>

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $(document).ready(function() {                                                   // When the HTML DOM is ready loading, then execute the following function...
        $('#calculator').submit(function() {                                         // Locate HTML element with ID "calculator" and execute the following function on its "submit" event...
            $form = $(this);                                                         // Wrap the form in a jQuery object first (so that special functions are available).
            $.post($form.attr('action'), $form.serialize(), function(responseText) { // Execute Ajax POST request on URL as set in <form action> with all input values of the form as parameters and execute the following function with Ajax response text...
                $('#result').text(responseText);                                     // Locate HTML element with ID "result" and set its text content with responseText.
            });
            return false;                                                            // Prevent execution of the synchronous (default) submit action of the form.
        });
    });
</script>

并更改最后两行,如下所示:doPost

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(String.valueOf(sum));

您甚至可以将其设置为条件检查,以便您的表单仍然适用于用户禁用了JS的情况:

    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
        // Ajax request.
        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(String.valueOf(sum));
    } else {
        // Normal request.
        request.setAttribute("sum", sum);
        request.getRequestDispatcher("calculator.jsp").forward(request, response);
    }

答案 2

我不确定这是否有帮助,但它至少是一个简单的计算器程序:

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    /* READ THE FIRST NUMBER FROM TEXTBOX NAMED num1 */
    Integer num1 = Integer.parseInt(request.getParameter("num1"));

    /* READ THE SECOND NUMBER FROM TEXTBOX NAMED num2 */
    Integer num2 = Integer.parseInt(request.getParameter("num2"));

    /* READ THE OPERATOR VALUE FROM SELECT TAG NAMED operator */
    String operator = request.getParameter("operator");

    /* THE FINAL RESULT */
    Integer result = 0;

    /* THE RESPONSE TO THE CLIENT WILL BE IN HTML FORMAT */
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    try {
        /* ALTERNATIVELY AN IF STATEMENT CAN ALSO BE USED
        if("+".equals(operator))
        {
            result = num1 + num2;
        }
        else if("-".equals(operator))
        {
            result = num1 - num2;
        }
        else if("*".equals(operator))
        {
            result = num1 * num2;
        }
        else if ("/".equals(operator))
        {
            result = num1 / num2;
        }
        */

        switch(operator)
        {
            case("+"): /* IF PLUS */
                result = num1 + num2;
                break;
            case("-"): /* IF MINUS */
                result = num1 - num2;
                break;
            case("*"): /* IF MULTIPLICATION */
                result = num1 * num2;
                break;
            case("/"): /* IF DIVISION */
                result = num1 / num2;
                break;
        }

        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet ServletCalculator</title>");
        out.println("</head>");
        out.println("<body>");
        /* THE PART OF OUTPUT TO THE CLIENT */
        out.println("<h1>" + num1 + " " + operator + " " + num2 + " = " + result + "</h1>");
        out.println("</body>");
        out.println("</html>");
    } finally {
        out.close();
    }
}

而 HTML 是:

<!DOCTYPE html>
<html>
    <body>
        <form action="ServletCalculator">
            Enter the first number <input name="num1" type="text"/>
            <select name="operator">
                <option value="+"> + </option>
                <option value="-"> - </option>
                <option value="*"> * </option>
                <option value="/"> / </option>
            </select>
            Enter the second number <input name="num2" type="text"/>
            <button type="submit"> Calculate </button>
        </form>
    </body>
</html>