0

I have a button in JSP, when clicked, goes to a servlet stores a java object using request.setAttribute("attr", object) and forwards to another page. In that page, I am using a custom JSP tag which gets this attribute and displays some values. Now I want this all to happen using AJAX. I want to have only one page which submits a form and receives an object to be used by custom JSP tag in the same page. How do I do this ? Is there a reliable library for that ?

From what I see, in ajax I can send response by printing it which means I must send an XML back. If I do so, how do I convert it back to java object so that JSP tag can use it ?

Prabhat
  • 2,261
  • 7
  • 46
  • 74

1 Answers1

2

Assuming your custom tag just displays some data, you could submit your form via ajax and return HTML. Then just push that HTML into a div. The HTML that is returned would be what your JSP with the custom tag renders, jQuery can help you out...

pseudo code:

$.post(url, params, function(htmlData) {
   $('#results').html(htmlData);
}); 

On the server side, nothing would really change from the way you are handling it now. If you don't need to post a form but just submit some data via ajax, you could also use the load() function.

Your ajax request will only return XML if you return XML. The response type is entirely up to you.

Gregg
  • 34,973
  • 19
  • 109
  • 214
  • Thanks for quick reply. The servlet returns a map of data which the elements inside my custom JSP tag use. Also, I dont want to use jquery. – Prabhat May 27 '11 at 04:33
  • Well, it doesn't matter how you make the AJAX request although I would use some sort of JavaScript library vs rolling your own. The point is, make the request via ajax, forward to your JSP with your custom tag, and in the response handler of your ajax call, plop that HTML on the page however you like. – Gregg May 27 '11 at 04:41
  • No. Technically, if I understand your initial question, nothing on the server side really needs to change. Currently, your JSP custom tag renders some HTML, correct? If yes, then you should be good as long as you handle things on the client correctly. Again, your servlet takes the request, does some data junk, forwards to your JSP with the custom tag. That is your response that will come back to the ajax response handler. – Gregg May 27 '11 at 04:48
  • The pattern of custom tag is like this. . Now I need to assign the map object in mainTag and in someTag I am accessing it by findAncestorWithClass() method. – Prabhat May 27 '11 at 04:50
  • All you said in your initial question is " I am using a custom JSP tag which gets this attribute and displays some values". If there are more details, then you need to edit your question and be more specific about what is going on. At this point, I don't know what else to tell you. My answer is accurate per your question. – Gregg May 27 '11 at 04:53