简体   繁体   中英

Spring ServletContext returns null

Stuck with the strange prob. I'm adding a ServletContext to my class (defined as @Service) and it always returns null. Tried both @Autowired and without it.

Also i didn't receive any error on app startup. Only the null value when i call 'servletContext.getRealPath("/WEB-INF/")'

This is a class where i'm trying to use it:

@Service
public class MyFactory  implements ServletContextAware {

    @Autowired
    ServletContext servletContext;

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

    private someMethod(){
       servletContext.getRealPath("/WEB-INF/"); //this return null
    }

}

PS servletContext itself is null, not a .getRealPath("/WEB-INF/") method

Your problem description is confusing. You say you add ServletContext and it returns null ( @Autowired or not), making it sound like the value of servletContext is null, when your wording and code example otherwise seems to indicate that getRealPath() is returning null.

If servletContext is null, then servletContext.getRealPath() will cause a NullPointerException .

If servletContext is not null, then servletContext.getRealPath() will succeed, but may return null.

Quoting javadoc of getRealPath() :

This method returns null if the servlet container is unable to translate the given virtual path to a real path.

So, if /WEB-INF/ is in a .war file that hasn't been unpacked, there is no real path, and getRealPath() will return null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM