使用Servlet处理AJAX请求? [英] Use a Servlet to handle AJAX requests?

查看:475
本文介绍了使用Servlet处理AJAX请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上是肯定或没有问题,但我也在寻求有关实施最佳实践的建议。

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.


  • 我有一个特定的Servlet(AjaxServlet?)来处理所有的AJAX请求

  • AjaxServlet映射到/ ajax / *所以像/ ajax / getDataFromServer这样的所有请求URL都将由它处理

  • 我的doGet overide函数是一个long if / elseif链,每次检查request.getPathInfo()

  • doGet中的每个if块处理特定的url调用(/ ajax / getDataFromServer)

  • I have a specific Servlet (AjaxServlet?) that will handle all AJAX requests
  • AjaxServlet maps to /ajax/* so all request URLs like /ajax/getDataFromServer will be handled by it
  • My doGet overide function is a long if/elseif chain checking the request.getPathInfo() each time
  • Each if block in doGet handles a specific url call (/ajax/getDataFromServer)

I想要返回JSON,到目前为止我一直在构建这些字符串。是否有我可以使用的轻量级JSON包。我知道我可以例如扩展ArrayList(ArrayListJson?)并添加一个toJson()方法,然后将任何ArrayList转换为ArrayListJson,但我确信这已经完成了。

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.

推荐答案

你的基本想法听起来不错,但最好有多个类,每个类都处理自己的任务。我成功使用的方法是使用单个servlet拦截调用,然后将任务传递给实际执行的其他类。例如,您可以创建一个接口(名为AJAXHandler),该接口具有方法 public String performTask(HttpServletRequest request),并使用servlet中的Factory Pattern实例化适当的类(实现AJAXHandler)并让该类完成它的工作。然后发送performTask方法(JSON字符串)的结果。当您需要实现新的AJAX调用时,您只需添加实现AJAXHandler的新类并使用新的类信息更新Factory。

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.

对于JSON处理,我建议你可以在 http://code.google.com/p/看看json-simple json-simple /

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

工厂模式描述于 http://www.oodesign.com/factory-pattern.html

祝你好运!!!

这篇关于使用Servlet处理AJAX请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆