对我来说似乎太大了
这实际上取决于上下文和功能要求。虽然它非常简单和微不足道。听起来这对您来说“信息太多”,并且您实际上需要单独学习单独的概念(HTTP、HTML、CSS、JS、Java、JSP、Servlet、Ajax、JSON 等) em> 以便更大的图景(所有这些语言/技术的总和)变得更加明显。你可能会发现this answer 很有用。
不管怎样,下面是你如何在没有 Ajax 的情况下只使用 JSP/Servlet 来做到这一点:
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 映射在 /calculator 的 url-pattern 上:
@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(请向右滚动查看代码 cmets,其中解释了每一行的作用):
<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 的情况下仍然有效:
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);
}