反射实现定位Servlet中的方法

public class BaseServlet extends HttpServlet{

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码表
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        // 接收参数:
        String methodName = req.getParameter("method");
        //如果method传递的参数为null或者为空字符串,作出提示
        if(methodName == null || "".equals(methodName)){
            resp.getWriter().println("method参数为null!!!");
            return;
        }
        // 获得子类的Class对象:
        /**
         * this.class代表加载继承了这个BaseServlet的class对象
         * */
        Class clazz = this.getClass();
        // 获得子类中的方法了:
        try {
            Method method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
            // 使方法执行,并获取子类return的字符串
            String path = (String)method.invoke(this, req,resp);
            //转发
            if(path != null){
                req.getRequestDispatcher(path).forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

原文地址:https://www.cnblogs.com/lychee-wang/p/9909673.html