First create a Servlet class that returns the desired response based on the request. It can be HTML, XML or JSON. I would suggest using JSON for this, as it is the simplest product that can be used in Java and consumed in JavaScript. You can use, for example, Google Gson to convert from a full-fledged Java object to a JSON string (and vice versa). For example.
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 to web.xml usual way. For example. on url-pattern of /firstServlet .
Then in jQuery you can use $.getJSON() to get the JSON from this resource. The first argument is the URL, which is obviously the firstServlet . The second argument is a callback function in which you can work with the returned response data. I passed the request parameter foo for the purposes of a clean demo, this is optional.
$.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 show a simple warning. For example. manupulating / traversing HTML DOM on the current page based on the returned data.
I posted two answers with practical examples before this, you may also find it useful:
- calling java servlet from javascript
- How to create dynamic dropdowns using jQuery and jsp?
Balusc
source share