First create a Servlet class which returns the desired response based on the request. It can be HTML, XML or JSON. I'd suggest to use JSON for this since that's the most easiest produceable in Java and consumeable in JavaScript. You can use for example Google Gson to convert from a fullworthy Java object to a JSON string (and vice versa). E.g.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOexception {
// Populate response data somehow. Can be a String, Javabean or Collection/Map of either.
Map<String, Object> data = new HashMap<String, Object>();
data.put("success", true);
data.put("message", "Hello World!");
data.put("param", request.getParameter("foo"));
// Write response data as JSON.
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(data));
}
Once the servlet is finished, just map it in web.xml
the usual way. E.g. on an url-pattern
of /firstServlet
.
Then, in jQuery you can use use $.getJSON()
to obtain JSON from the given resource. The first argument is the URL, which is obviously firstServlet
. The second argument is the callback function wherein you can work on the returned response data. I've passed the request parameter foo
for pure demonstration purposes, this is not mandatory.
$.getJSON('firstServlet?foo=bar', function(data) {
alert('Success: ' + data.success + '\n'
+ 'Message: ' + data.message + '\n'
+ 'Param: ' + data.param);
});
You can of course do more with this than just displaying a simple alert. E.g. manupulating/traversing the HTML DOM in the current page based on the returned data.
I've posted two answers with practical examples before here, you may find it useful as well: