public class ServletHelper extends HttpServlet {
//重写了父类中的service方法。其他servlet继承此类,会自动执行此类的service,不用重复写请求分发
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获得Servlet配置的路径
//System.out.println(req.getServletPath());
System.out.println(req.getRequestURL());
//获得当次请求的路径
String requestURI = req.getRequestURI();
//就去到请求的最后一个地址
String path = requestURI.substring(requestURI.lastIndexOf('/')+1);
/*
通过反射,使用字符串方法名,获取方法对象
*/
try {
//获取当前类指定方法名的方法
Method declaredMethod = this.getClass().getDeclaredMethod(path,HttpServletRequest.class,HttpServletResponse.class);
//执行
declaredMethod.invoke(this,req,resp);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
//如果没有找到方法, 会报NoSuchMethodException
//此时,设置报错页面,跳转到404
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
}