我想在jsp中创建一个简单的计算器。将有两个用于数字的文本框和一个添加按钮。理想情况下,我希望答案不重新加载就显示在页面中,但是从我得到的答案来看,它似乎对我的规模来说太大了。我可以想到:1)将答案打印到第三个文本框(有可能吗?),或者以某种方式将答案与相同的页面(带有添加按钮和全部)一起加载(并能够输入不同的数字,依此类推) 。
您能建议一个好的方法吗?
对于我的规模来说似乎太大了
这实际上取决于上下文和功能要求。这是非常简单和琐碎的。它更多的声音一样,它的“太多信息”为你和你实际需要学习不同的概念(HTTP,HTML,CSS,JS,Java和JSP,Servlet的,AJAX,JSON等) 单独 使大局观(所有这些语言/技术的总和)变得更加明显。您可能会发现此答案很有用。
无论如何,这是仅使用JSP / Servlet而不使用Ajax的方法:
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>
用CalculatorServlet其被映射上url-pattern的/calculator:
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中包含以下JS <head>(请向右滚动以查看代码注释,其中解释了每一行的作用):
<head>
<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如下更改最后两行:
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); }