简单的计算器在JSP中 [英] Simple calculator in JSP

查看:347
本文介绍了简单的计算器在JSP中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是排序延续我的 previous问题的,但我觉得它应该得到特别的,因为我得到了非常详细的回答是自己。

我想创建JSP一个简单的计算器。将有两个文本框的数量和添加按钮。理想情况下,我希望出现在页面答案,而无需重新加载,但是从我得到的答复,似乎太大了,我的规模。我能想到的两种:1)打印答案第三个文本框(这是可能的),或以某种方式加载在同一页(使用Add按钮和所有)的答复(并且能够进入不同的号码等)?

您能否提供一个很好的办法做到这一点?

解决方案
  

似乎太大了,我的规模

这真的取决于上下文和功能要求。这是pretty的简单,琐碎,但。它更像是这对你和说:太多的信息的声音,你真正需要学习不同的概念(HTTP,HTML,CSS,JS,爪哇,JSP,Servlet的,AJAX,JSON等)的单独这样的大局观(所有语言/技术的总和)变得更加明显。您可能会发现<一href="http://stackoverflow.com/questions/1958808/java-web-development-what-skills-do-i-need/1958854#1958854">this回答有用的话。

总之,这里的你怎么可以只用JSP / Servlet的没有Ajax做到这一点:

calculator.jsp

&LT;形式ID =计算器行动=计算器的方法=邮报&GT;     &其中p为H.;         &LT; =左&GT输入名称;         &LT;输入名称=权与GT;         &LT;输入类型=提交值=加上&GT;     &所述; / P&GT;     &其中p为H.;结果:其中;跨度的id =结果&GT; $ {总和}&所述; /跨度&GT;&所述; / P&GT; &LT; /形式GT;

CalculatorServlet 被映射到一个 URL模式的 /计算器

@覆盖 保护无效的doPost(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{     整数左= Integer.valueOf(的request.getParameter(左));     整数右= Integer.valueOf(的request.getParameter(正确));     整数总和=左+右;     了request.setAttribute(求和,总和); //这将是可作为$ {}总和。     的request.getRequestDispatcher(calculator.jsp)向前(请求,响应)。 //重新显示JSP。 }


制作Ajaxical东西做工也并不难。这里面包括以下JS的问题在JSP的HTML &LT; HEAD&GT; (请滚动到见code评论该部分解释了每一行做正确的)

&LT;脚本SRC =HTTP://$c$c.jquery.com/jquery-latest.min。 JS&GT;&LT; / SCRIPT&GT; &LT;脚本&GT;     $(文件)。就绪(函数(){//当HTML DOM是准备好装载,然后执行以下功能...         $('#计算器)。递交(函数(){//找到ID为计算器HTML元素和它的提交事件中执行以下功能...             $形式= $(本); //裹在一个jQuery对象第一的形式(这样的特殊功能可用)。             $。员额($ form.attr('行动'),$ form.serialize()函数(responseText的){// URL上执行的Ajax POST请求的设置与&lt;形式的作用&gt;的形式为所有输入值参数,并执行与Ajax响应文本下面的函数...                 $('#结果)文本(responseText的); //找到HTML元素的ID为结果,并将其文本内容与responseText的。             });             返回false; // prevent执行同步(默认值)提交表单的动作。         });     }); &LT; / SCRIPT&GT;

和改变的最后两行的doPost 如下:

response.setContentType(text / plain的);     response.setCharacterEncoding(UTF-8);     。response.getWriter()写(将String.valueOf(和));

您甚至可以使一个条件检查,使您的窗体仍适用于该用户有JS禁用的情况下:

如果(XMLHtt prequest.equals(request.getHeader(X-要求,随着)) ){         // Ajax请求。         response.setContentType(text / plain的);         response.setCharacterEncoding(UTF-8);         。response.getWriter()写(将String.valueOf(和));     } 其他 {         //正常请求。         了request.setAttribute(求和,总和);         的request.getRequestDispatcher(calculator.jsp)向前(请求,响应)。     }

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

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

这篇关于简单的计算器在JSP中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆