/**
* @author 王磊
* @date 2022/4/26
* 自定义Servlet完成请求分发
*/
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求路径
String uri = req.getRequestURI();
// lastIndexOf 从最右边开始找,找到"/"第一次出现的索引位置
int index = uri.lastIndexOf("/");
//进行字符串截取,为什么要加1,因为通过运行我们发现路径上有个/ 我们是不需要的
String methodName = uri.substring(index + 1);
//通过反射机制获取类的字节码文件 this:谁调用我,我就代表谁
Class<?extends BaseServlet> cls = this.getClass();
try {
Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//执行方法
method.invoke(this,req,resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
手写springmvc
最新推荐文章于 2025-06-09 15:00:51 发布