Home

Tue, Nov. 29th, 2005, 01:39 pm
Spring and JSP

Our team is currently developing a Java Web application. I've just introduced them to Spring and Hibernate, so learning them both plus a web framework would be too much, so they're using JSP for the presentation layer, since it's closer to what they know (PHP, ASP, etc).

Today, they've asked me how can I access a Spring Bean from inside a JSP page?. Since I've never worked directly with JSP, I had to research a little. I found a good idiom for it in a post by mfisher in the Spring Framework Support Forums, which I reproduce here:

In general, you should minimize application code's awareness of the beanFactory. Dependencies should be injected in the service layer so that Controllers (Servlets) may use (or delegate to) objects loaded by the beanFactory. Objects may be returned to the view layer, but the views (JSPs) should not access the beanFactory directly to retrieve objects.

All that said, there are ways to access the ApplicationContext via the ServletContext. For using Spring in a web application, there is a ContextLoaderListener which is specified in web.xml as:

<listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

That will look in the default location of: WEB-INF/applicationContext.xml.
For a different name or location, you need to add:

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>WEB-INF/someOtherFilename.xml</param-value>
</context-param>

The ApplicationContext can then be retrieved via the static method:

WebApplicationContextUtils.getWebApplicationContext(servletContext)

The accessibility of ApplicationContext via ServletContext is primarily for the purpose of the framework itself, and as mentioned above following "best practice" design will reduce or eliminate the need to acces the beanFactory from within application code.