This is sort of a continuation of my previous question, but I feel it deserved to be on its own, especially because of the very detailed answer I got.
I would like to create a simple calculator in JSP. There will be two textboxes for numbers and an add button. Ideally, I want the answer to appear in the page without reloading, but from the answer I got, it seems too big for my scale. I can think of either: 1) print the answer to a third textbox (is this possible?) or somehow loading the same page (with the add button and all) with the answer (and be able to enter different numbers and so on).
What is a good way to do this?
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); // It'll be available as ${sum}.
request.getRequestDispatcher("calculator.jsp").forward(request, response); // Redisplay JSP.
}
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() { // 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>
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"))) {
// 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);
}
I'm not sure if this can help, but it is at least a simple calculator program:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/* READ THE FIRST NUMBER FROM TEXTBOX NAMED num1 */
Integer num1 = Integer.parseInt(request.getParameter("num1"));
/* READ THE SECOND NUMBER FROM TEXTBOX NAMED num2 */
Integer num2 = Integer.parseInt(request.getParameter("num2"));
/* READ THE OPERATOR VALUE FROM SELECT TAG NAMED operator */
String operator = request.getParameter("operator");
/* THE FINAL RESULT */
Integer result = 0;
/* THE RESPONSE TO THE CLIENT WILL BE IN HTML FORMAT */
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
/* ALTERNATIVELY AN IF STATEMENT CAN ALSO BE USED
if("+".equals(operator))
{
result = num1 + num2;
}
else if("-".equals(operator))
{
result = num1 - num2;
}
else if("*".equals(operator))
{
result = num1 * num2;
}
else if ("/".equals(operator))
{
result = num1 / num2;
}
*/
switch(operator)
{
case("+"): /* IF PLUS */
result = num1 + num2;
break;
case("-"): /* IF MINUS */
result = num1 - num2;
break;
case("*"): /* IF MULTIPLICATION */
result = num1 * num2;
break;
case("/"): /* IF DIVISION */
result = num1 / num2;
break;
}
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet ServletCalculator</title>");
out.println("</head>");
out.println("<body>");
/* THE PART OF OUTPUT TO THE CLIENT */
out.println("<h1>" + num1 + " " + operator + " " + num2 + " = " + result + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
And the HTML is:
<!DOCTYPE html>
<html>
<body>
<form action="ServletCalculator">
Enter the first number <input name="num1" type="text"/>
<select name="operator">
<option value="+"> + </option>
<option value="-"> - </option>
<option value="*"> * </option>
<option value="/"> / </option>
</select>
Enter the second number <input name="num2" type="text"/>
<button type="submit"> Calculate </button>
</form>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With