Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 <a href="http://www.hunlock.com/blogs/Mastering_JSON_%28_JavaScript_Object_Notation_%29" rel="nofollow noreferrer">JSON</a> for this since that's the most easiest produceable in Java and consumeable in JavaScript. You can use for example <a href="http://code.google.com/p/google-gson/" rel="nofollow noreferrer">Google Gson</a> to convert from a fullworthy Java object to a JSON string (and vice versa). E.g.</p> <pre><code>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&lt;String, Object&gt; data = new HashMap&lt;String, Object&gt;(); 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)); } </code></pre> <p>Once the servlet is finished, just map it in <code>web.xml</code> the usual way. E.g. on an <code>url-pattern</code> of <code>/firstServlet</code>. </p> <p>Then, in jQuery you can use use <a href="http://api.jquery.com/jQuery.getJSON/" rel="nofollow noreferrer"><code>$.getJSON()</code></a> to obtain JSON from the given resource. The first argument is the URL, which is obviously <code>firstServlet</code>. The second argument is the callback function wherein you can work on the returned response data. I've passed the request parameter <code>foo</code> for pure demonstration purposes, this is not mandatory.</p> <pre><code>$.getJSON('firstServlet?foo=bar', function(data) { alert('Success: ' + data.success + '\n' + 'Message: ' + data.message + '\n' + 'Param: ' + data.param); }); </code></pre> <p>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.</p> <p>I've posted two answers with practical examples before here, you may find it useful as well:</p> <ul> <li><a href="https://stackoverflow.com/questions/3028490/calling-a-java-servlet-from-javascript">calling a java servlet from javascript</a></li> <li><a href="https://stackoverflow.com/questions/2896730/how-to-generate-dynamic-drop-down-lists-using-jquery-and-jsp">How to generate dynamic drop down lists using jQuery and jsp?</a></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload