java.lang.NoSuchMethodException异常解决

在MVC中使用转发地址栏不发生变化,而使用BaseController反射原理是,地址栏解析出来的方法名为转发之前的地址栏名称,所以在反射时出现java.lang.NoSuchMethodException异常。而使用重定向则地址栏发生变化。利用发射可以成功解析出方法名。c

   protected void displayInterface(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String searchKeywords = req.getParameter("searchKeywords");
        if (searchKeywords == null){
            searchKeywords = "";
        }
        //查询全部书籍
        //查询页码和每页显示大小
        String pageNoStr = req.getParameter("pageNo");
        String pageSizeStr = req.getParameter("pageSize");
        int pageNo = 1;
        if(pageNoStr != null){
            pageNo = Integer.valueOf(pageNoStr);
        }
        int pageSize = 5;
        if (pageSizeStr != null){
            pageSize = Integer.valueOf(pageSizeStr);
        }
        Page page = bookService.queryBookByPage(pageNo, pageSize,searchKeywords);
        page.setSearchKeywords("searchKeywords="+searchKeywords);
        page.setQueryUrl("bookstore/displayInterface");
        HttpSession session = req.getSession();
        session.setAttribute("searchKeywords",searchKeywords);
        session.setAttribute("PageInfo",page);
        session.setAttribute("searchKeywords",searchKeywords);
       // req.setAttribute("searchKeywords",searchKeywords);
       // req.setAttribute("PageInfo",page);
        // req.getRequestDispatcher("/displayInterface.jsp").forward(req,resp);
        resp.sendRedirect("/displayInterface.jsp");
    }

 此例中,在最后代码区域,(注释代码)使用转发,地址栏为发生变化。通过BaseController来解析会产生java.lang.NoSuchMethodException异常。而使用重定向地址栏发生变化。则可以成功解析方法名。

 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        String[] split = requestURI.split("/");
        String methodName = split[split.length - 1];
        //使用 反射 通过方法名获取下面的方法
        Class aClass = this.getClass();
        try {
            //获取方法
            Method declaredMethod = aClass.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //暴力 破解方法的访问修饰符
            declaredMethod.setAccessible(true);
            //执行方法
            declaredMethod.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

  • 14
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值