import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class BaseServlet extends HttpServlet { //重写service方法 根据请求路径进行方法的分发 而不是根据原本的请求方式 @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1.首先获取请求的路径 String uri = req.getRequestURI(); // uri : brand-case/brand/selectAll //1.1 获取路径最后的方法名 //返回字符串最后出现的索引 int index = uri.lastIndexOf("/"); //返回/selectAll //1.2 获取方法名 //String substring(int beginIndex) 返回一个字符串,该字符串是此字符串的子字符串。 String methodName = uri.substring(index + 1); //2.执行方法 //2.1获取方法的对象 BrandServlet //利用反射 获取对象 // com.itheima.web.servie.BrandServlet@5389c3aa this指向的对象 //this: 谁调用我(谁使用我这个类)我(BrandServlet)就是谁 //下面<? extends BaseServlet> extends Class<? extends BaseServlet> aClass = this.getClass(); //获取反射对象的方法组 try { Method method = aClass.getMethod(methodName,HttpServletRequest.class , HttpServletResponse.class); method.invoke(this,req,resp); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } }
关于反射 BaseServlet 根据路径进行方法的分发
最新推荐文章于 2025-03-14 08:56:16 发布