tags:

views:

386

answers:

4

Hi Folks,

We need some input on what is a good design pattern on using AJAX in a Java application.

Consider a simple scenario:

  1. User clicks a button which sends a request to a Java method to fetch data from DB.
  2. Java object is returned by method and needs to be converted into a HTML table.
  3. HTML table is shown on JSP.

What we currently do:

  1. On a JSP page, user clicks "Show Users" button
  2. Button using Prototype.js calls a "middleman" JSP which forwards the request to the Java method to get the data from the DB.
  3. The method returns the Java object to the "middleman" JSP which converts the Java object into HTML (since the AJAX call from the calling JSP won't be able to handle the Java object directly).
  4. The HTML is then returned to the Prototype call which updates the div on the calling JSP.

Our concerns are:

  1. We would like to keep the separation of business/presentation logic and would prefer no HTML/JavaScript code inside our Java methods.
  2. Keeping (1) in mind, is having a "middleman" JSP an OK way to do this? Or should we return the Java object as XML/XSLT to the AJAX request?
  3. The above way we're doing has very little JavaScript and works in all browsers.
  4. We looked at some other packages - DWR, GWT, but either there was too much dependency on JavaScript or required UI components to be present in the Java classes.

Is our way of doing things above OK? Or is there another preferable way?

Any help/thoughts would be appreciated.

Thanks,

SP

+1  A: 

Sounds fine. You are separating view components from model components. It shouldn't matter how the call comes to the server, AJAX or not, it should be received by a controller (a servlet say) that interacts with the model, thats your Java classes that get the data from the database and forward to a JSP page for rendering the view.

There are frameworks that could simplify the boilerplate code but the design you describe sounds fine.

Vincent Ramdhanie
A: 

Vincent, thanks for your reply. Just the confirmation we were looking for.

Thanks, SP

spie
A: 

I'm not sure if you noticed, but there's one significant difference between your solution and what Vincent proposed. This is that the request should be initially received by a servlet (or controller, or Struts action, etc.) rather than a "middleman" JSP.

MVC dictates that JSPs should really only we used for generating the view from the model data, flow control is better handled in Java code.

Don
A: 

Don, yes I did catch that ... we were planning on going that route as well. Thanks for the follow-up though.

Regards,

SP

spie