0

I created a simple Hello World Spring MVC project.

I added the below lines in my web.xml

<init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/spring-servlet.xml</param-value>         
</init-param>

My code is working without these lines. I don't understand the purpose of adding these lines. Can anyone please explain me its usage in simple words.

Joginder Pawan
  • 659
  • 3
  • 10
  • 19

3 Answers3

2

On initialization of a DispatcherServlet, look for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and create the beans defined there (overriding the definitions of any beans defined with the same name in the global scope).

For example,

<web-app>
  <servlet>
   <servlet-name>
       spring
   </servlet-name>
       <servlet-lass>org.springframework.web.servlet.DispatcherServlet
   </servlet-class>
   <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>
       spring
    </servlet-name>
   <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

With the above servlet configuration in place, you will need to have a file called '/WEB-INF/spring-servlet.xml' and it will automatically picked.

But for different servlet name and configuration file name or location we must need to provide file name and location while initializing the Dispatcher servlet as given below.

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

    <servlet-mapping>
        <servlet-name>SpringController</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

(Here servlet name is SpringController and configuration file name is spring-servlet.xml. Even, here you can use any name for your configuration file for example, my_spring_mvc_configurtaion.xml)

1

By default Spring looks for the following file to load its web context:

{my-sevlet-name}-servlet.xml

So it seems like that you named your Spring's DispatcherServlet 'spring'. In this case Spring simply loads spring-servlet.xml and the lines you mention doesn't affect the app at all.

Dmitry Senkovich
  • 5,521
  • 8
  • 37
  • 74
0

The initialization parameter contextConfigLocation tells Spring where to load configuration files. If it works without that code in web.xml means somewhere in your java code this configuration file is getting loaded.