how to show jsp in response to an ajax call to a servlet [duplicate]
i am sending search parameters to a search servlet using ajax and that servlet is searching the database. now i am dispatching the request to SearchResults.jsp where i am showing the results.
String nextJSP = "/s/SearchResults.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request, response);
The problem is that i am getting full jsp in response to the ajax call , but i want the SearchResults.jsp page to be opened with the results after the ajax call.
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
There is a similiar question: best practice to render JSON data in JSPs? This is sample for json to return json data: http://code.google.com/p/json-simple/wiki/JSPAndAJAXExamples Also there is some jsp tab lib like:http://json-taglib.sourceforge.net/
In short, you can control what to output in the jsp by juding the request accept type.
精彩评论