Draymonders / Code-Life

The marathon continues though.
27 stars 3 forks source link

Servlet 阅读理解 #69

Open Draymonders opened 4 years ago

Draymonders commented 4 years ago

Servlet

最基础的

servlet  用来接收请求&返回响应

servletConfig servlet初始化的一些参数配置

servletContext servlet容器里有多个servlet,所有servlet共享一个servletContext

GenericServlet 是实现了servletservletConfig, 并且做了简单的优化

例如
public void init(ServletConfig config) throws ServletException {
    this.config = config;
    this.init();
}
// 这样实现servlet的时候,就不用调用super.init(config)了,因为 init(config)中调用了 init()
public void init() throws ServletException {}

HttpServlet 实现了 GenericServlet

HttpServlet是个抽象类,其子类需要实现doGet, doPost, doPut, doDelete方法任一,不实现的默认返回 方法不可用 以doHead方法为例(doHead,即发来一个请求, 返回空响应)

protected void doHead(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
{
    NoBodyResponse response = new NoBodyResponse(resp);

    doGet(req, response);
    response.setContentLength();
}

欣赏一下 getAllDeclaredMethods

private Method[] getAllDeclaredMethods(Class<? extends HttpServlet> c) {
    Class<?> clazz = c;
    Method[] allMethods = null;

    while (!clazz.equals(HttpServlet.class)) {
        Method[] thisMethods = clazz.getDeclaredMethods();
        if (allMethods != null && allMethods.length > 0) {
            Method[] subClassMethods = allMethods;
            allMethods =
                new Method[thisMethods.length + subClassMethods.length];
            // 这里是将thisMethods copy到 allMethods
            System.arraycopy(thisMethods, 0, allMethods, 0,
                                thisMethods.length);
            // 再将subClassMethos copy到 allMethods
            System.arraycopy(subClassMethods, 0, allMethods, thisMethods.length,
                                subClassMethods.length);
        } else {
            allMethods = thisMethods;
        }

        clazz = clazz.getSuperclass();
    }

    return ((allMethods != null) ? allMethods : new Method[0]);
}
Draymonders commented 4 years ago

TODO Tomcat源码阅读

2020.08.08留坑