Spirng-Mvc之Servlet篇

在java中有一个javax.servlet.Servlet接口,这个接口中存在5个方法,分别是:

public interface Servlet {
  //当容器启动时被调用,只调用一次(当load-on-startup设置为负数或者不设置时,会在servlet第一次用到时才会调用init)   
public void init(ServletConfig config);   //用于获取ServletConfig   public ServletConfig getServletConfig();   //用于处理具体的一个请求   public void service(ServletRequest req, ServletResponse res) throws ServletException, IOExcetpion;   //获取一些servlet相关的信息,如版权,作者等。默认为空   public String getServletInfo();   //用于servlet销毁时释放一些资源,也只调用一次   public void destory(); }

init方法被调用时会接收到一个ServletConfig类型的参数,时容器传进去的。

那么这个ServletConfig参数是什么时候配置的呢?

我们在web.xml中定义servlet时通过init-param标签配置的参数就是通过ServletConfig类型来保存的。

<servlet>
    <servlet-name>servletDemo</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>spring.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Tomcat中servlet的init方法是在org.apache.catalina.core.StandardWrapper的initServlet方法中调用的。

ServletConfig的入参是StandardWrapperFace类(由于ServletConfig的参数是由配置文件设置的,这样StandardWrapper就包含了对应的配置,但是StandarWrapper中又不是所有的内容都和Config有关,所以延伸出了StandaraWrapperFace类)

public  interface ServletConfig{
 //获取Servlet的名字,也就是servlet-name
public String getServletName(); //用于获取init-param对应的参数,而返回值ServletContext就是应用本身,既然是应用本身,那么设置在其中的参数就会被应用中所有的serlvet共享
public ServletContext getServletContext();
public String getInitParameter(String name); public Enumeration<String> getInitParameterNames(); }

ServletConfig和ServletContext最常见的使用场景之一是传递初始化参数。

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>application-spring.xml</param-value>
</context-param>
<servlet>
    <servlet-name>servletDemo</servlet-name>
    <servlet-class>com.demo.DemoServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>spring.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

以上案例中context-param标签中的参数设置到了ServletContext中,而下方的servlet中的init-param的参数则是设置到了ServletConfig中

在Servlet中可以分别通过它们对应的getInitParameter()获取

例:

  String contextLocation = getServletConfig().getServletContext().getInitParameter("contextConfigLocation");

  String configLocation = getServletConfig().getInitParameter("contextConfigLocation");

原文地址:https://www.cnblogs.com/culushitai/p/10692452.html