我个人使用反射在我的控制器(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)
查看[Apache Struts](http://struts.apache.org/primer.html)和[MVC模式](http://java.sun.com/blueprints/guidelines/) designing_enterprise_applications_2e/Web层/ WEB-tier5.html)。 –