2018-05-18 利用反射将多个请求对应到一个Servlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.获取ServletPath:/addCustomer.do
        String servletPath=request.getServletPath();
        //2.去除/和.do,得到类似于addCustomer这样的字符串
        String methodName=servletPath.substring(1);
        methodName=methodName.substring(0,methodName.length()-3);
        
        try {
            //3.利用反射获取methodName对应的方法
            Method method=getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
            //4.利用反射调用对应的方法
            method.invoke(this, request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }

你可能感兴趣的:(2018-05-18 利用反射将多个请求对应到一个Servlet)