it seems too big for my scale
That really depends on the context and the functional requirements. It's pretty simple and trivial though. It more sounds like that it's "too much info" for you and that you actually need to learn the separate concepts (HTTP, HTML, CSS, JS, Java, JSP, Servlet, Ajax, JSON, etc) individually so that the bigger picture (the sum of all those languages/techniques) becomes more obvious. You may find this answer useful then.
Anyway, here's how you could do it with just JSP/Servlet without 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>
with CalculatorServlet
which is mapped on an url-pattern
of /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);
request.getRequestDispatcher("calculator.jsp").forward(request, response);
}
Making Ajaxical stuff to work is also not that hard. It's a matter of including the following JS inside the JSP's HTML <head>
(please scroll to the right to see code comments which explains what every single line does):
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#calculator').submit(function() {
$form = $(this);
$.post($form.attr('action'), $form.serialize(), function(responseText) {
$('#result').text(responseText);
});
return false;
});
});
</script>
and changing the last two lines of doPost
as follows:
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(String.valueOf(sum));
You can even make it a conditional check so that your form still works for the case that user has JS disabled:
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(String.valueOf(sum));
} else {
request.setAttribute("sum", sum);
request.getRequestDispatcher("calculator.jsp").forward(request, response);
}