how to get getServletContext() in spring mvc Controller how to get getServletContext() in spring mvc Controller java java

how to get getServletContext() in spring mvc Controller


  1. Use below code to autowire ServletContext object in SpringMVC

    @AutowiredServletContext context; 

    and after that try to execute your code like

    String uploadPath = context.getRealPath("") + File.separator + UPLOAD_DIRECTORY;
  2. You can get it in your controller like this;

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

    but for this your controller must implement ServletContextAware interface


Try this:

@AutowiredServletContext servletContext;


This is just another alternative

((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext()