本帖最后由 980041382 于 2021-10-16 18:28 编辑
java.lang.NoSuchMethodException: cn.itcast.travel.web.servlet.UserServlet.add(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletRequest)
at java.lang.Class.getDeclaredMethod(Class.java:2158)
at cn.itcast.travel.web.servlet.BaseServlet.service(BaseServlet.java:28)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
这是BaseServlet
[Java] 纯文本查看 复制代码 package cn.itcast.travel.web.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//System.out.println("baseServlet的service方法被执行了...");
//完成方法分发
//1.获取请求路径
String uri = req.getRequestURI(); // 返回/travel/user/add
System.out.println("请求uri:"+uri); // /user/add
//2.获取方法名称
String methodName = uri.substring(uri.lastIndexOf('/') + 1);
System.out.println("方法名称:"+methodName);
//3.获取方法对象Method
//this 谁调用我?我代表谁
System.out.println(this);//UserServlet的对象cn.itcast.travel.web.servlet.UserServlet@16dc326f
try {
//忽略访问权限修饰符,获取方法
Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletRequest.class);
//4.执行方法
//暴力反射
//method.setAccessible(true);
method.invoke(this,req,resp);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
这是UserServlet
[Java] 纯文本查看 复制代码 package cn.itcast.travel.web.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("userServlet的add方法");
}
public void find(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("userServlet的find方法");
}
}
无论是使用getDeclaredMethod()还是getMethod()都会报这个错误,把Protected设置成Public也还是会报错
求助!
是自己太粗心了。。。 |