Monday, January 4, 2016

How to get ServletContext and ServletConfig object in a Spring Bean?

Ref:- http://howtodoinjava.com/2015/03/02/spring-mvc-interview-questions-with-answers/

Simply implement ServletContextAware and ServletConfigAware interfaces and override below methods.
@Controller
@RequestMapping(value = "/magic")
public class SimpleController implements ServletContextAware, ServletConfigAware {
 
    private ServletContext context;
    private ServletConfig config;
 
    @Override
    public void setServletConfig(final ServletConfig servletConfig) {
        this.config = servletConfig;
 
    }
 
    @Override
    public void setServletContext(final ServletContext servletContext) {
        this.context = servletContext;
    }
     
    //other code
}

1 comment:

  1. Thank you for this amazing answer Rajesh,
    I have one question, will this make SimpleController as prototype bean since every request will have its own ServletContext.
    Thanks
    Maneesh

    ReplyDelete