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.
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()
}
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.
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";
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With