如何在servlet之间推广方法调用?

时间:2013-05-09 07:49:14

标签: 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.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类的函数中,但我无法正确的方法。

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

UserController.class.getDeclaredMethod(string,args)返回方法,如果它在类UserController中声明。

您可以使所有servlet类由父servlet继承,如Funtik建议的那样,然后在超类中添加此方法:

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调用这个静态方法时,你应该将this.getClass()作为参数传递。

您还可以查看http://code.google.com/p/bo2/source/browse/trunk/Bo2Utils/main/gr/interamerican/bo2/utils/ReflectionUtils.java。它包含一些您需要的实用程序(查找方法,执行它等)

答案 1 :(得分:-1)

你试过继承吗?

在其中创建一个抽象的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 {
 }
相关问题