How to get Spring WebContext in annotated @controller class

In Spring MVC with annotation, we mark any POJO with @Controller. In this controller, we can get the WebApplicationContext using the autwired 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 a servlet. User-friendly interface. So is it possible to use the old way to get WebApplicationContext? i.e.

 WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext) 

How do we get servletContext here?

I do not encounter any compulsion to use the old method; so this question is just out of curiosity to check spring's flexibility. It may also be an interview question.

+8
spring spring-mvc servlets autowired applicationcontext
source share
5 answers

You can simply enter it into your controller:

 @Autowired private ServletContext servletContext; 

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

 @RequestMapping(...) public ModelAndView myMethod(HttpServletRequest request ...){ ServletContext servletContext = request.getServletContext() } 
+16
source share

The right approach:

 @Autowired ServletContext context; 

Otherwise, instead of automatically posting ServletContext, you can implement ServletContextAware. Spring will notice this when working in the context of a web application and insert a ServletContext. Read this .

+2
source share

You can also do this inline:

 @RequestMapping(value = "/demp", method = RequestMethod.PUT) public String demo(@RequestBody String request) { HttpServletRequest re3 = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); return "sfsdf"; } 
+2
source share

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 servletContext anywhere in the class.

+2
source share

Having accessed the session, you can get the servlet context, example code:

 @Controller public class MyController{ .... @RequestMapping(...) public ModelAndView myMethod(HttpSession session ...){ WebApplicationContextUtils.getRequiredWebApplicationContext(session.getServletContext()) } } 

You can also get HttpSession from HttpServletRequest.

+1
source share

All Articles