本文介绍了使用JSP / Servlet和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.

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

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

你能建议一个好方法吗?

Can you suggest a good way to do this?

推荐答案

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

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.

无论如何,这里是如何使用没有Ajax的JSP / Servlet来实现的:

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>

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的问题(请向右滚动以查看解释每行代码的代码注释):


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>

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

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

您甚至可以将其作为条件检查,以便您的表单仍适用于用户拥有JS的情况已禁用:

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

这篇关于使用JSP / Servlet和Ajax的简单计算器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 21:41