// BaseServlet
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取请求路径
String uri = req.getRequestURI();
System.out.println(uri);
//2.获取最后一段路径,方法名
String methodName = uri.substring(uri.lastIndexOf("/")+1);
System.out.println(methodName);
//字节码对象 Class
//谁调用我(this所在的方法),我(this)代表谁
Class<? extends BaseServlet> cls = this.getClass();
Method method = null;
//3.获取method对象
try {
method = cls.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
//4.执行方法
method.invoke(this,req,resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
BrandServlet
@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet{
public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("brand selectAll");
}
public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
System.out.println("brand add");
}
}