Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Servlet from a JSP page using jQuery Ajax [duplicate]

I know there are quite a few related question here but none that actually relate to my question have an answer attached. Or at least an accepted answer. Happy to be wrong in this if someone can point me to the question. Also please retag if I've miss-tagged.

My question, as the title says is that I want to call a Servlet from my JSP page and return a string, or html.

My Servlet name is MyFirstServlet.

Could you please, please be very specific in any answers as I am a complete JSP, Java and Servlet noobie.

Thank you very much in advance.

like image 542
griegs Avatar asked Sep 01 '10 02:09

griegs


1 Answers

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:

  • calling a java servlet from javascript
  • How to generate dynamic drop down lists using jQuery and jsp?
like image 83
BalusC Avatar answered Oct 21 '22 06:10

BalusC