2

I want to add a servlet context parameter/attribute through spring configuration. I need this because the value I want to add in servlet context is available only after spring container loads. I'm adding the value inside the servlet context as I need the value in almost all my .jsp files.

Essentially I need a mechanism opposite to this

Community
  • 1
  • 1
Amit Goyal
  • 454
  • 4
  • 10
  • You can't add servlet context parameters programmatically, there's no API for that. Why can't your Spring controllers just add the values to the model before forwarding to the view? – skaffman Jun 04 '10 at 13:56
  • Actually, you can... check out the javadocs for ServletContext, namely setAttribute(String,Object). – cjstehno Jun 04 '10 at 16:47

1 Answers1

9

Assuming you are using a properly configured Spring Web Application Context, you could try implementing a bean that implements org.springframework.web.context.ServletContextAware and org.springframework.beans.factory.InitializingBean so that you could add whatever you want to the ServletContext in the afterPropertiesSet method implementation.

public class ServletContextInjector implements ServletContextAware,InitializingBean {
    private ServletContext servletContext;

    public void setServletContext(ServletContext sc){ this.servletContext = sc; }

    public void afterPropertiesSet(){
        servletContext.setAttribute( /* whatever */ );
    }
}

Hope this helps.

cjstehno
  • 13,468
  • 4
  • 44
  • 56