Servlet源码初探

时间:2022-07-06 18:18:07

  年底,公司的事情告一段落,就来捣鼓一下这个Servlet源码,为下一步的spingmvc源码初探做准备

1、Servlet接口

public interface Servlet {

    void init(ServletConfig var1) throws ServletException;

    ServletConfig getServletConfig();

    void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;

    String getServletInfo();

    void destroy();
}

2、ServletConfig接口

public interface ServletConfig {
String getServletName(); ServletContext getServletContext(); String getInitParameter(String var1); Enumeration<String> getInitParameterNames();
}

3、抽象类GenericServlet

public abstract class GenericServlet implements Servlet, ServletConfig, Serializable{
.
.
.
.
  public String getInitParameter(String name) {
ServletConfig sc = this.getServletConfig();
if(sc == null) {
throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
} else {
return sc.getInitParameter(name);
}
}
  public ServletConfig getServletConfig() {
return this.config;
} public ServletContext getServletContext() {
ServletConfig sc = this.getServletConfig();
if(sc == null) {
throw new IllegalStateException(lStrings.getString("err.servlet_config_not_initialized"));
} else {
return sc.getServletContext();
}
}
}

4、抽象类HttpServlet

public abstract class HttpServlet extends GenericServlet {
......
}

5、解释

  一个servlet对应一个ServletConfig,该接口由容器实现,比如Tomcat,封装了servlet的初始化信息,每一个ServletConfig中有一个获取ServletContext引用的方法,而一个web应用的所有Servlet共享同一个ServletContext所以该对象被称为application对象,我们在web项目中新建的一个servlet只需继承自抽象类HttpServlet就可以调用this.getServletConfig().getInitParameter(String name)和this.getServletContext().getInitParameter(String name)这两个方法,这两个方法获取值的区别:

1、this.getServletConfig().getInitParameter(String name)

<!-- Spring MVC配置 -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> 2、this.getServletContext().getInitParameter(String name) <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:spring-context.xml</param-value>
</context-param>

  这两个参数是Springmvc配置的基本参数。