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

发布于 2024-10-01 07:42:15 字数 330 浏览 3 评论 0原文

这是我的上一个问题的延续,但我觉得这是值得的独立,特别是因为我得到了非常详细的答案。

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

有什么好的方法可以做到这一点?

This is sort of a continuation of my previous question, but I feel it deserved to be on its own, especially because of the very detailed answer I got.

I would like to create a simple calculator in JSP. There will be two textboxes for numbers and an add button. Ideally, I want the answer to appear in the page without reloading, but from the answer I got, it seems too big for my scale. I can think of either: 1) print the answer to a third textbox (is this possible?) or somehow loading the same page (with the add button and all) with the answer (and be able to enter different numbers and so on).

What is a good way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

半岛未凉 2024-10-08 07:42:15

对于我的规模来说似乎太大了

这实际上取决于上下文和功能需求。虽然它非常简单和微不足道。听起来这对您来说“信息太多”,您实际上需要学习单独的概念(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>

使用映射到 url-patternCalculatorServlet > of /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(请滚动到右侧查看代码注释,其中解释了每一行的作用):

<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>

并更改 < 的最后两行code>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);
    }

it seems too big for my scale

That really depends on the context and the functional requirements. It's pretty simple and trivial though. It more sounds like that it's "too much info" for you and that you actually need to learn the separate concepts (HTTP, HTML, CSS, JS, Java, JSP, Servlet, Ajax, JSON, etc) individually so that the bigger picture (the sum of all those languages/techniques) becomes more obvious. You may find this answer useful then.

Anyway, here's how you could do it with just JSP/Servlet without Ajax:

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>

with CalculatorServlet which is mapped on an url-pattern of /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.
}

Making Ajaxical stuff to work is also not that hard. It's a matter of including the following JS inside the JSP's HTML <head> (please scroll to the right to see code comments which explains what every single line does):

<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>

and changing the last two lines of doPost as follows:

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

You can even make it a conditional check so that your form still works for the case that user has JS disabled:

    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);
    }
能否归途做我良人 2024-10-08 07:42:15

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

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>

I'm not sure if this can help, but it is at least a simple calculator program:

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();
    }
}

And the HTML is:

<!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>
∞琼窗梦回ˉ 2024-10-08 07:42:15

也许,最简单的方法是创建一个包含两个字段和一个提交按钮的 表单。在服务器端,您可以添加两个数字并打印它。

像这样的东西:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    int a = Integer.valueOf(request.getParameter("a"));
    int b = Integer.valueOf(request.getParameter("b"));
    int res = a + b;
    response.getWriter().println(res);
}

Probably, the simplest way will be create a form with two fields and a submit button. On the server side you can add two numbers and print it.

Something like:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    int a = Integer.valueOf(request.getParameter("a"));
    int b = Integer.valueOf(request.getParameter("b"));
    int res = a + b;
    response.getWriter().println(res);
}
娇纵 2024-10-08 07:42:15

这绝对可以做到,并且可以使用简单的 HTML 和 JavaScript 来完成。为此,您可以避免使用服务器端 Java 计算。

在我看来,我们应该尽量保持服务器上的负载最小。当可以在客户端完成此操作时,请勿加载服务器。

简单的计算,如加法、减法、乘法和除法,可以通过编写 JavaScript 函数来实现,如 add(a, b)、sub(a, b)、mul(a, b)、div(a, b)。并且这些函数可以在不同的按钮单击事件上调用。

This can absolutely be done and can be done using simple HTML and JavaScript. You can avoid using server side Java calculation for this.

In my opinion, we should try to maintain the least load on the server. Don't load the server when this can be done at the client side.

Simple calculations, like addition, subtraction, multiplication and division, can be attained by writing JavaScript functions like add(a, b), sub(a, b), mul(a, b), div(a, b). And these functions can be called on different button click events.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文