Calling a servlet from a JSP page using jQuery Ajax

I know that there are many related questions, but not one that really relates to my question has an answer. Or at least the accepted answer. Happy to be wrong about this if someone can point me to a question. Also, please repeat if I missed the mark.

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

My servlet name is MyFirstServlet.

Could you please be very specific in the answers since I am full of JSP, Java and Servlet noobie.

Thank you in advance.

+6
jquery jsp servlets
source share
1 answer

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?
+8
source share

All Articles