Matthew
Matthew

Reputation: 8416

Use a Servlet to handle AJAX requests?

Basically a yes or no question but I am also looking for advice on best practices for implementation.

Let me know when/if I start to go wrong.

I want to return JSON and so far I have been building these strings myself. Is there a lightweight JSON package I could use. I know I could for example extend ArrayList (ArrayListJson?) and add a toJson() method and then cast any ArrayList to ArrayListJson but I'm sure this has been done already.

Upvotes: 3

Views: 1503

Answers (3)

Mike
Mike

Reputation: 318

Your basic idea sounds OK, but it would be best to have multiple classes that each handle their own task. A method I have used successfully is to use a single servlet to intercept the call, then pass the task to some other class that actually does the implementation. For example, you could create an interface (named, say, AJAXHandler) that has a method public String performTask(HttpServletRequest request) and use the Factory Pattern in your servlet to instantiate the appropriate class (that implements AJAXHandler) and let that class do its work. The results from the performTask method (the JSON string) is then sent out. When you need a new AJAX call implemented, you just add the new class that implements AJAXHandler and update the Factory with with the new class info.

For JSON handling, I suggest you take a look at json-simple, at http://code.google.com/p/json-simple/

The Factory pattern is described at http://www.oodesign.com/factory-pattern.html

Good Luck!!!

Upvotes: 5

r0ast3d
r0ast3d

Reputation: 2635

I would say go for REST instead of the long if/else if chain on the servlet also that gives you more control to assemble services to be used.

Upvotes: 0

karnyj
karnyj

Reputation: 1222

If you are looking for a lightweight solution to replace your big IF block, you could use reflection to call methods on an object based on request parameters.
as for json for java:http://json.org/java/

Upvotes: 0

Related Questions