My name is Vasyl Khrystiuk‎ > ‎process‎ > ‎main‎ > ‎

Get Spring context everywhere

in costum tag:
	protected WebApplicationContext _applicationContext;
	
	protected WebApplicationContext getSpringContext() throws JspException{
		PageContext pageContext = (PageContext) getJspContext();
		if(_applicationContext==null){
			_applicationContext = RequestContextUtils.getWebApplicationContext(
					pageContext.getRequest(),
					pageContext.getServletContext()
				);
		}
		return _applicationContext;
	}

Three other options:
http://mythinkpond.wordpress.com/2010/03/22/spring-application-context/

From request outside of DispatcherServlet based on session:
WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(httpSession.getServletContext());


public class MyServlet extends HttpServlet {

  @Autowired
  private MyService myService;

  public void init(ServletConfig config) {
    super.init(config);
    SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
      config.getServletContext());
  }
}

Another solution is configure the application context to export the Spring bean to the servlet context as an attribute:

<bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
  <property name="attributes">
    <map>
      <entry key="jobbie" value-ref="springifiedJobbie"/>
    </map>
  </property>
</bean>

Your servlet can retrieve the bean from the servlet context using

SpringifiedJobbie jobbie = (SpringifiedJobbie) getServletContext().getAttribute("jobbie");

Getting request object:
ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
HttpServletRequest req = sra.getRequest();





Comments