对于我的体重秤来说,它似乎太大了
这实际上取决于上下文和功能要求。不过,这非常简单和琐碎。这听起来更像是“信息太多”,你实际上需要单独学习单独的概念(HTTP,HTML,CSS,JS,Java,JSP,Servlet,Ajax,JSON等),以便更大的图景(所有这些语言/技术的总和)变得更加明显。你可能会发现这个答案很有用。
无论如何,以下是如何在没有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
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>
<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);
}