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();
        }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容