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: