栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

对于我的规模来说似乎太大了

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

无论如何,这是仅使用JSP / Servlet而不使用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

@Overrideprotected 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中包含以下JS

<head>
(请向右滚动以查看代码注释,其中解释了每一行的作用):

<script src="http://pre.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);    }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464708.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号