9

In Spring MVC with annotation, we mark any POJO with @Controller. In this controller we can get WebApplicationContext, using autowired property.

@Controller
public class HomePageController {

@Autowired
ApplicationContext act;

    @RequestMapping("/*.html")
    public String handleBasic(){
        SimpleDomain sd = (SimpleDomain)act.getBean("sd1");
        System.out.println(sd.getFirstProp());
        return "hello";
}

But in this approach we do not have servletContext handy with us. So is there way we can still use older way of getting WebApplicationContext ? i.e.

WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)

How will we get servletContext here ?

I am not facing any compulsion to use old way; so this question is just out of curiosity to check flexibility of spring. Also It can be a interview question.

tereško
  • 58,060
  • 25
  • 98
  • 150
Kaushik Lele
  • 6,439
  • 13
  • 50
  • 76

5 Answers5

16

You can just inject it into your controller:

@Autowired private ServletContext servletContext;

Or take HttpServletRequest as a parameter and get it from there:

@RequestMapping(...)
public ModelAndView myMethod(HttpServletRequest request ...){
    ServletContext servletContext = request.getServletContext()
}
Biju Kunjummen
  • 49,138
  • 14
  • 112
  • 125
2

The following is correct approach :

@Autowired
ServletContext context;

Otherwise instead of auto wiring the ServletContext, you can implement ServletContextAware. Spring will notice this when running in a web application context and inject the ServletContext. Read this.

Jeevan Patil
  • 6,029
  • 3
  • 33
  • 50
2

You can also do it inline:

@RequestMapping(value = "/demp", method = RequestMethod.PUT)
public String demo(@RequestBody String request) {
    HttpServletRequest re3 = ((ServletRequestAttributes) RequestContextHolder

            .getRequestAttributes()).getRequest();
    return "sfsdf";
 }
Guy L
  • 2,824
  • 2
  • 27
  • 37
2

You can implement an Interface from Spring called org.springframework.web.context.ServletContextAware

public class MyController implements ServletContextAware {
    private ServletContext servletContext; 

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

Then you can use the servletContext any place in the class.

sendon1982
  • 9,982
  • 61
  • 44
1

By accessing the session you can get the servlet context, sample code:

@Controller
public class MyController{

....
@RequestMapping(...)
public ModelAndView myMethod(HttpSession session ...){

WebApplicationContextUtils.getRequiredWebApplicationContext(session.getServletContext())

}

}

You can get the HttpSession from the HttpServletRequest also.

ElderMael
  • 7,000
  • 5
  • 34
  • 53