对于我的规模来说似乎太大了
这实际上取决于上下文和功能要求。这是非常简单和琐碎的。它更多的声音一样,它的“太多信息”为你和你实际需要学习不同的概念(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); }


