2012-06-29 33 views
2

我目前正在制作Java Servlet,可以响应jquery调用并发回数据供我的网页使用。但这只是使用doGet方法的回应。Java Servlet和Jquery

有没有在Servlet中有多种方法的方法,并用JQuery分别调用它们?

即有一个叫做Hello的方法,它返回一个String“Hello”和另一个叫做Bye的方法,它返回一个String“Bye”。有没有办法使用jquery或其他一些技术来做这种事情?

我对servlets很新,所以我仍然不确定它们完全有能力。那么doGet是“进入”的唯一方法,我只是从那里分支回应?

+0

查看[Apache Struts](http://struts.apache.org/primer.html)和[MVC模式](http://java.sun.com/blueprints/guidelines/) designing_enterprise_applications_2e/Web层/ WEB-tier5.html)。 –

回答

0

我个人使用反射在我的控制器(servlet的),基本上让我实现这一目标。

如果我有一个叫做UserController的

的主URL调用servlet会/用户的servlet。 知道这一点,我总是通过我的第一个参数?action = add

然后在我的servlet中有一个名为add或actionAdd的方法。无论你喜欢什么。

然后我使用下面的代码;

String str = String str = request.getParameter("action").toLowerCase(); 
Method method = getClass().getMethod(str, HttpServletRequest.class, HttpServletResponse.class); 
method.invoke(this, request, response); 

说明:

海峡将有动作参数值,加上在这种情况下。 方法方法将是对具有给定名称(str)及其预期参数类型的方法的引用。

然后我调用方法,传递上下文,请求和响应。

add方法看起来像这样;

public void add(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { 
    //do add stuff 

     String url = "/user/index.jsp"; 
     RequestDispatcher dispatcher = context.getRequestDispatcher(url); 
     request.setAttribute("User", user); 
     dispatcher.forward(request, response); 
} 

我不知道只传回一个字符串。但是这应该为你提供一个基本的想法。

请注意,反射可能会让你付出代价,所以它不应该真的影响你很像这样。由于方法名称/签名需要完美匹配,因此很容易出错。

所以从jQuery的,你会做一个Ajax请求的网址:

localhost/projectname/user/add (if you use urlrewrite) 
or 
localhost/projectname/user?action=add (if you dont) 
0

Servlet容器支持的Servlet以来3.0自定义Http方法。对于实施例,

public void doHello(HttpServletRequest req, HttpServletResponse res) { 
    //implement your custom method 
} 

在Servlet的上述方法可使用hello HTTP方法被调用。

但我不确定jquery是否支持调用自定义HTTP方法。

如果它没有,那么你唯一的选择。

  • 使用GET和操作参数调用Servlet。
  • 读取操作参数并使用反射调用该方法。