Simple Calculator with Jsp/Servlet and Ajax

Simple calculator with JSP/Servlet and Ajax

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);
}

Jquery Ajax call to servlet

you must add the success param to ajax function


$.ajax({
type: "POST",
url: "/ArchiveSearch/Search",
dataType: "json",
data: formData,
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});

How to send a single Ajax request instead of two

As per the comments, you just need to let the first request forward to the desired JSP instead of returning the JSON string which you in turn pass back to the JSP.

request.getRequestDispatcher("/WEB-INF/next.jsp?jsonstring=" + jsonstring).forward(request, response);

how to show jsp in response to an ajax call to a servlet

Don't use JSP for this. It's good for HTML stuff only. Just let the servlet return JSON or XML and process it in JS side. Here's a kickoff example assuming that you want to search for products and that the Product class has properties name, description and price which you'd like to show in a table.

products.jsp

<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 5336889</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#search').submit(function() {
$.get(this.action, $(this).serialize(), function(products) {
var $table = $('<table>').appendTo($('#results'));
$.each(products, function(index, product) {
var $tr = $('<tr>').appendTo($table);
$('<td>').text(product.name).appendTo($tr);
$('<td>').text(product.description).appendTo($tr);
$('<td>').text(product.price).appendTo($tr);
});
});
});
});
</script>
</head>
<body>
<form id="search" action="products">
Search products:
<input name="query" />
<input type="submit" />
</form>
<div id="results"></div>
</body>
</html>

In combination with a servlet which listens on an URL pattern of /products:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products = productDAO.find(request.getParameter("query"));
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(products));
}

(where Gson is Google Gson).

See also:

  • Updating page with ajax and servlets
  • Ajax calculator example

how to loop over values in servlets and display them in them table?

My solution would be to use a list of strings to store the history. If you want a better solution, you could write a class that has first, second, and operator so that you can retrieve each property. I store the list in the session so that it can be accessed by the JSP page. I'm just writing a minimal solution. It's up to you to rewrite it to meet your requirements.

JSP page

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<form action="ComputeServlet" method="post">
<input type="text" name="firstNumber" size="5">
<select name="operator">
<option value="+">+</option>
<option value="+">-</option>
<option value="+">*</option>
<option value="+">/</option>
</select>
<input type="text" name="secondNumber" size="5">
<input type="submit" name="submit" value="submit">

<c:forEach var="problem" items="${history}">
<p>${problem}</p>
</c:forEach>
<input type="submit" name="clear" value="clear">
</form>

Servlet

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

if (request.getParameter("clear")!=null){
List<String> history = (List<String>) request.getSession().getAttribute("history");
if (history == null){
history = new ArrayList<>();
request.getSession().setAttribute("history", history);
} else {
history.clear();
}
} else if (request.getParameter("submit")!=null){
int first = Integer.parseInt(request.getParameter("firstNumber"));
int second = Integer.parseInt(request.getParameter("secondNumber"));
String op = request.getParameter("operator");
int result = 0;
switch(op){
case "+": result = first+second; break;
case "*": result = first*second; break;
case "/": result = first/second; break;
case "-": result = first-second; break;
}
List<String> history = (List<String>) request.getSession().getAttribute("history");
if (history == null){
history = new ArrayList<>();
request.getSession().setAttribute("history", history);
}
history.add("" + first + op + second + "=" + result);
}
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}

Output

<form action="ComputeServlet" method="post">
<input type="text" name="firstNumber" size="5">
<select name="operator">
<option value="+">+</option>
<option value="+">-</option>
<option value="+">*</option>
<option value="+">/</option>
</select>
<input type="text" name="secondNumber" size="5">
<input type="submit" name="submit" value="submit">

<p>4+5=9</p>
<p>2+6=8</p>
<p>3+2=5</p>
<p>3+2=5</p>

<input type="submit" name="clear" value="clear">
</form>

Sample Image

how to consume json object in a servlet that has been passed in the ajax request

There's a huge misunderstanding here. The way how you sent the ajax request doesn't end up in a JSON object in the server side at all. All the data is just available by request.getParameter() the usual way. The $.serialize() merely collects all input values of the form into a JSON object which is in turn behind the scenes by $.ajax encoded as HTTP query string the usual way. The JSON object is merely an intermediary format which allows you to very easily submit the entire form using $.ajax.

So, the data of

<form id="registrationForm" ...>
<input name="foo" ... />
<input name="bar" ... />
<input name="baz" ... />
</form>

can in the servlet just be collcted exactly the same way as if it were a synchronous (a regular) submit

String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
String baz = request.getParameter("baz");
// ...

Please note that the dataType option instructs the jQuery $.ajax() as which data type the response should be treated. It has totally no relationship with how the data is been sent by the request. It's just been sent as HTTP request parameters the usual way. See also $.ajax() documentation.

See also:

  • Simple calculator with JSP/Servlet and Ajax
  • Ajax program form username validation in java
  • How to use Servlets and Ajax?


Related Topics



Leave a reply



Submit