Java 带有 JSP/Servlet 和 Ajax 的简单计算器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4114742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:45:45  来源:igfitidea点击:

Simple calculator with JSP/Servlet and Ajax

javajavascriptajaxjspservlets

提问by Amir Rachum

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

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

Can you suggest a good way to do this?

你能提出一个很好的方法来做到这一点吗?

采纳答案by BalusC

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) individuallyso that the bigger picture (the sum of all those languages/techniques) becomes more obvious. You may find this answeruseful then.

这实际上取决于上下文和功能要求。不过,这非常简单和琐碎。它更多的声音一样,它的“太多信息”为你和你实际需要学习不同的概念(HTTP,HTML,CSS,JS,Java和JSP,Servlet的,AJAX,JSON等)单独使大局观(所有这些语言/技术的总和)变得更加明显。你可能会发现这个答案很有用。

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

无论如何,这里是您如何在不使用 Ajax 的情况下仅使用 JSP/Servlet 来实现的方法:

calculator.jsp:

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 CalculatorServletwhich is mapped on an url-patternof /calculator:

CalculatorServlet其被映射上url-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.
}


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

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

and changing the last two lines of doPostas follows:

并将最后两行更改doPost如下:

    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:

您甚至可以进行条件检查,以便您的表单仍然适用于用户禁用 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);
    }

回答by Stan Kurilin

probably, the simplest way will be create formwith two fields and submit button. In server side you can add two numbers and print it. Smt like:

可能,最简单的方法是创建具有两个字段的表单和提交按钮。在服务器端,您可以添加两个数字并打印出来。Smt 喜欢:

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

回答by Bikash Rath

This can absolutely be done and can be done using simple html and javascript. You can avoid using server side java calculation for this.

这绝对可以完成,并且可以使用简单的 html 和 javascript 来完成。您可以避免为此使用服务器端 java 计算。

In my opinion, we should try to maintain least load on the server. Why to 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 dfferent button click events.

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

回答by xameeramir

I'm not sure if this can help but it is atleast 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 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

和 html 是

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