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

时间:2010-11-06 19:21:43

标签: java javascript ajax jsp servlets

这是我previous question的延续,但我觉得它应该独立,特别是因为我得到了非常详细的答案。

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

你能建议一个好方法吗?

4 个答案:

答案 0 :(得分:23)

  

对我的比例来说似乎太大了

这实际上取决于背景和功能要求。虽然它很简单而且微不足道。听起来更像是“太多信息”,而你实际上需要单独学习单独的概念(HTTP,HTML,CSS,JS,Java,JSP,Servlet,Ajax,JSON等)因此,更大的图片(所有这些语言/技术的总和)变得更加明显。您可能会发现this answer非常有用。

无论如何,这里是你如何使用没有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>

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

让Ajaxical工作起来也不是那么难。这是在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>

并更改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);
    }

答案 1 :(得分:3)

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

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

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

答案 2 :(得分:2)

可能,最简单的方法是使用两个字段和提交按钮创建form。在服务器端,您可以添加两个数字并打印它。 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);
}

答案 3 :(得分:1)

这绝对可以完成,可以使用简单的html和javascript完成。您可以避免使用服务器端Java计算。

在我看来,我们应该尝试在服务器上保持最少的负载。为什么在客户端可以加载服​​务器?

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