0
点赞
收藏
分享

微信扫一扫

手写springmvc

小布_cvg 2022-04-27 阅读 59
springjava

/**
 * @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();
        }

    }
}
举报

相关推荐

0 条评论