Wednesday, February 15, 2012

Spring 3 : Servlet Context and other Context beans.

Here I will try to explain following question about ServletContext and Other Context beans in a spring application.

1. Why do we need a ServletContext?
2. Why do we need an ApplicationContext?
3. Do we need them both in a spring 3 application?
4. Most Common use of a ServletContext.
5. Most Common use of an ApplicationContext.

ServletContext:
For any spring application a servlet context is must which we define in spring-servlet.xml or myapp-servlet.xml file. When a servlet starts it looks for its context definition and load the context. Most of the cases we define following components in a servlet context.

<!-- Notify the servlet to load the components using annotation, 
for example '@controller' -->
<mvc:annotation-driven/>

<!-- Load the beans/controllers into context from base-package and 
Map requests from '@RequestMapping' annotation. -->
<context:component-scan base-package="com.mycompany.helloSpring3.web" />

<!-- This defination is used to create ModelAndView object by servlet. -->
<bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
</bean>
ApplicationContext:
This is an optional Context. In fact there may multiple context files in an application as per need. Usually we put the dataSource related definitions in this file.

Note: If we need to use additional Context files along with the ServletContext, In that case we need to tell our servlet-descriptor(web.xml) to load them with a ContextLoaderListener.
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/*Context.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

1 comment:

Luis Gutierrez said...

Excellent contribution. Solvent error I had.