《架構(gòu)探險(xiǎn)-從零還是寫JavaWeb框架》——黃勇 讀書筆記
遇到問題
- 第3章 搭建輕量級(jí)Java Web框架
此章節(jié)閱讀完成后,根據(jù)書中的代碼,demo案例是無法跑起來的。經(jīng)過斷點(diǎn)調(diào)試,發(fā)現(xiàn)如下代碼處有問題:
問題描述:java.lang.IllegalArgumentException: wrong number of arguments
問題位置:Object result = ReflectUtil.invokeMethod(controllerBean, actionMethod, param);
分析:ReflectUtil.invokeMethod 方法中調(diào)用了 method.invoke 方法,此處的入?yún)胁⑽醋鱿鄳?yīng)處理,所以報(bào)錯(cuò)
解決方法:
- 將代碼
Object result = ReflectUtil.invokeMethod(controllerBean, actionMethod, param);修改為Object result = ReflectUtil.invokeMethod(controllerBean, actionMethod, null);,這樣可以保證項(xiàng)目正常啟動(dòng),MVC功能也可以用,但是Controller傳參無效。 - 繼續(xù)閱讀,因?yàn)榻酉聛韼讉€(gè)章節(jié)會(huì)對(duì)代碼進(jìn)行優(yōu)化,希望可以解決此問題。
// 代碼來自框架:DispatcherServlet.java
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
// 獲取請(qǐng)求方法和請(qǐng)求路徑
String requestMethod = req.getMethod().toLowerCase();
String requestPath = req.getPathInfo();
// 獲取action處理器
Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
if (null != handler) {
// 獲取controller類,及其Bean實(shí)例
...
String body = CodecUtil.decodeURL(StreamUtil.getString(req.getInputStream()));
if (StringUtil.isNotEmpty(body)) {
...
}
Param param = new Param(paramMap);
// 調(diào)用action方法
Method actionMethod = handler.getActionMethod();
Object result = ReflectUtil.invokeMethod(controllerBean, actionMethod, param);
if (result instanceof View) {
// 返回jsp頁面
...
} else if (result instanceof Data) {
// 返回json數(shù)據(jù)
...
}
}
}