简体   繁体   English

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

[英]Simple calculator with JSP/Servlet and Ajax

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. 我想在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). 我可以想到:1)打印第三个文本框的答案(这可能吗?)或以某种方式加载相同的页面(使用添加按钮和所有)和答案(并能够输入不同的数字等) 。

Can you suggest a good way to do this? 你能建议一个好方法吗?

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. 它更多的声音这样说,这是“太多的信息”为你和你实际需要分别学习不同的概念(HTTP,HTML,CSS,JS,Java和JSP,Servlet的,AJAX,JSON等),这样的大局观(所有这些语言/技术的总和)变得更加明显。 You may find this answer useful then. 你可能会发现这个答案很有用。

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 CalculatorServlet which is mapped on an url-pattern of /calculator : 使用CalculatorServlet映射到/calculatorurl-pattern

@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. 让Ajaxical工作起来也不是那么难。 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): 这是在JSP的HTML <head>中包含以下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>

and changing the last two lines of doPost as 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);
    }

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>

probably, the simplest way will be create form with two fields and submit button. 可能,最简单的方法是使用两个字段创建表单并提交按钮。 In server side you can add two numbers and print it. 在服务器端,您可以添加两个数字并打印它。 Smt 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);
}

This can absolutely be done and can be done using simple html and javascript. 这绝对可以完成,可以使用简单的html和javascript完成。 You can avoid using server side java calculation for this. 您可以避免使用服务器端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). 通过编写诸如add(a,b),sub(a,b),mul(a,b),div(a,b)之类的javascript函数,可以实现诸如加法,减法,乘法和除法之类的简单计算。 And these functions can be called on dfferent button click events. 并且可以在不同的按钮点击事件上调用这些函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM