public abstract interface Servlet {
public abstract void init(ServletConfig paramServletConfig) throws ServletException;
init方法在容器启动的时候被调用,当load-on-startup设置为负数或者不设置时会在servlet第一次被访问的时候调用,并且只会被调用一次。
init被调用时候会传入一个ServletConfig类型的参数,是容器传进去的。也就是servlet的配置信息
比如web.xml,下方init-param配置的信息就是通过ServletConfig来保存。
在定义springMvc的Servlet,指定配置文件位置的参数contextConfigLocation就是存放在ServletConfig中。
public abstract ServletConfig getServletConfig();
该方法用于获取Servlet的配置文件
public abstract void service(ServletRequest paramServletRequest, ServletResponse paramServletResponse)
throws ServletException, IOException;
具体处理一个请求
public abstract String getServletInfo();
获取servlet相关的一些信息,如作者版权,这个方法需要自己实现,默认返回空字符串。
public abstract void destroy();
servlet销毁,或服务器关闭时候调用。只会调用一次。
}
ServletConfig接口
public abstract interface ServletConfig {
public abstract String getServletName();
用于获取servlet的名字,也就是web.xml中配置的servlet-name
public abstract ServletContext getServletContext();
返回的是这个应用本身,它里面的所有参数都可用被当前应用的所有Servlet共享。
我们在项目中,参数可以保存在session中,也可以保存在Application中。其实保存在Application中就是保存在ServletContext中
ServletConfig是servlet级的,一般地只是保存配置参数
而ServletContext是Context级的,并不只是保存配置参数,还有其他的功能。
public abstract String getInitParameter(String paramString);
用于获取用init-param配置的参数
public abstract Enumeration<String> getInitParameterNames();
用于获取配置文件中所有init-param的名字的集合
}
web.xml片段:
<!-- springmvc的前端控制器 -->
<servlet>
<servlet-name>selfstudy</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation,
springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- springmvc的前端控制器 -->
<servlet>
<display-name>initParam Demo</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>application-context.xml</param-value>
</context-param>
<servlet-name>selfstudy</servlet-name>
<servlet-class>com.study.springmvn</servlet-class>
<!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation,
springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
这个例子:
通过context-param配置的contextConfigLocation配置到了ServletContext中
通过servlet下init-param的contextConfigLocation配置到了ServlerConfig中
在Servlet中可以分别通过它们的getInitParameter方法获取
String contextLocation = getServletConfig().getServletContext().getInitParameter("contextConfigLocation");
String servletLocation = getServletConfig().getInitParameter("contextConfigLocation");