JavaWeb 反射 NoSuchMethodException异常解决方案
问题描述:
在编写JavaWeb程序时,报错情况如下:找不到要执行的类
我使用的工具:
- IDEA
报错情景:
- JavaWeb 写Servlet使用反射调用方法时,报错位置如下:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
try {
Method action_method = this.getClass().getDeclaredMethod("action",
HttpServletRequest.class,HttpServletResponse.class);
action_method.invoke(this, req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
下面开始说明可能产生错误的原因:
-
<div class="form"> <form action="userServlet" method="post"> <input type="hidden" name="action" value="login_doPost" /> <label>用户名称:</label> <input class="itxt" type="text" placeholder="请输入用户名" autocomplete="off" tabindex="1" name="username" value="${requestScope.username}"/> <br /> </form> </div>
看到隐藏域中的name为action的value的值是不是你要调用的方法,是否写错等
-
web.xml中是否做了相应配置
-
是不是在这里加了“”号
这里加了引号之后就会出现错误,把引号去掉之后才会调用 action 对应的 value 的值,如果有引号,只会调用方法名为 action 的方法,自然会找不到。