《架构探险-从零还是写JavaWeb框架》——黄勇 读书笔记

2019-08-14  本文已影响0人  和女朋友一起开发的游戏

《架构探险-从零还是写JavaWeb框架》——黄勇 读书笔记

遇到问题

  1. 第3章 搭建轻量级Java Web框架

此章节阅读完成后,根据书中的代码,demo案例是无法跑起来的。经过断点调试,发现如下代码处有问题:

问题描述:java.lang.IllegalArgumentException: wrong number of arguments

问题位置:Object result = ReflectUtil.invokeMethod(controllerBean, actionMethod, param);

分析:ReflectUtil.invokeMethod 方法中调用了 method.invoke 方法,此处的入参书中并未做相应处理,所以报错

解决方法:

  1. 将代码 Object result = ReflectUtil.invokeMethod(controllerBean, actionMethod, param); 修改为 Object result = ReflectUtil.invokeMethod(controllerBean, actionMethod, null);,这样可以保证项目正常启动,MVC功能也可以用,但是Controller传参无效。
  2. 继续阅读,因为接下来几个章节会对代码进行优化,希望可以解决此问题。
// 代码来自框架:DispatcherServlet.java
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // 获取请求方法和请求路径
    String requestMethod = req.getMethod().toLowerCase();
    String requestPath = req.getPathInfo();
    // 获取action处理器
    Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
    if (null != handler) {
        // 获取controller类,及其Bean实例
        ...
        String body = CodecUtil.decodeURL(StreamUtil.getString(req.getInputStream()));
        if (StringUtil.isNotEmpty(body)) {
            ...
        }
        Param param = new Param(paramMap);
        // 调用action方法
        Method actionMethod = handler.getActionMethod();
        Object result = ReflectUtil.invokeMethod(controllerBean, actionMethod, param);
        if (result instanceof View) {
            // 返回jsp页面
            ...
        } else if (result instanceof Data) {
            // 返回json数据
            ...
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读