Java 如何在servlet中推广方法调用?

Java 如何在servlet中推广方法调用?,java,servlets,reflection,Java,Servlets,Reflection,我的一个控制器中的doPost()中包含以下代码。此代码基本上从请求中获取action参数,并执行与action值同名的方法 // get the action from the request and then execute the necessary // action. String action = request.getParameter("action"); try { Method method = UserController.class

我的一个控制器中的
doPost()
中包含以下代码。此代码基本上从请求中获取
action
参数,并执行与action值同名的方法

// get the action from the request and then execute the necessary
    // action.
    String action = request.getParameter("action");
    try {
        Method method = UserController.class.getDeclaredMethod(action,
                new Class[] { HttpServletRequest.class,
                        HttpServletResponse.class });
        try {
            method.invoke(this, request, response);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    } catch (SecurityException e) {

        e.printStackTrace();
    } catch (NoSuchMethodException e) {

        ErrorHandlingHelper.redirectToErrorPage(response);
        e.printStackTrace();
    }
现在我想在我所有的控制器中实现这个功能。我试图将其推广到
helper
类中的函数中,但我无法找到正确的方法


我怎样才能做到这一点?

您尝试过继承吗

制作一个抽象的ParentServlet并覆盖其中的
doPost()
方法。 所有其他servlet都应该继承自
ParentServlet

所以这应该是这样的:

 public abstract class ParentServlet extends HttpServlet {
     ...
     protected void doPost(HttpServletRequest req, HttpServletResponse resp){
        //your action logic here
     }
 }


 public class ChildServlet extends ParentServlet {
 }

getDeclaredMethod(string,args)返回在类UserController中声明的方法

您可以按照Funtik的建议,让所有servlet类由父servlet继承,然后在超类中添加此方法:

protected Method methodToInvoke(String action) {
    Class[] args =  { HttpServletRequest.class,
                    HttpServletResponse.class };
    Method method = this.getClass().getDeclaredMethod(action, args);
}
此方法搜索以查找正在执行的servlet类(This.getClass())的方法。您还可以在supertype sevlet类中包含执行方法

或者,如果您不想或不能将所有servlet子类化,您可以将此功能放在实用程序类中,但是您应该将servlet类作为参数传递

protected static Method methodToInvoke(String action, Class clazz) {
    Class[] args =  { HttpServletRequest.class,
                    HttpServletResponse.class };
    Method method = clazz.getDeclaredMethod(action, args);
}
但是,当您从servlet调用此静态方法时,应该将此.getClass()作为参数传递


你也可以看看。它包含一些您需要的实用程序(查找方法、执行方法等)

当我调用子servlet时,它永远不会调用父servlet的
doPost
。这是怎么回事?你怎么会这么想?如果未在ChildServlet中定义doPost()方法,则将执行父级的doPost()。如果在子对象中有doPost()方法,只需调用super.doPost()即可