[英]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.我正在向我的类(定义为 @Service)添加一个 ServletContext,它总是返回 null。 Tried both @Autowired and without it.尝试了@Autowired 和没有它。
Also i didn't receive any error on app startup.此外,我在应用程序启动时没有收到任何错误。 Only the null value when i call 'servletContext.getRealPath("/WEB-INF/")'只有当我调用 '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 PS servletContext
本身为空,不是.getRealPath("/WEB-INF/")
方法
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.您说您添加了ServletContext
并且它返回 null( @Autowired
与否),这听起来像是servletContext
的值是 null,否则您的措辞和代码示例似乎表明getRealPath()
返回 null。
If servletContext
is null, then servletContext.getRealPath()
will cause a NullPointerException
.如果servletContext
为 null,则servletContext.getRealPath()
将导致NullPointerException
。
If servletContext
is not null, then servletContext.getRealPath()
will succeed, but may return null.如果servletContext
不为 null,则servletContext.getRealPath()
将成功,但可能返回 null。
Quoting javadoc of getRealPath()
:引用getRealPath()
javadoc :
This method returns
null
if the servlet container is unable to translate the given virtual path to a real path.如果 servlet 容器无法将给定的虚拟路径转换为真实路径,则此方法返回null
。
So, if /WEB-INF/
is in a .war file that hasn't been unpacked, there is no real path, and getRealPath()
will return null.因此,如果/WEB-INF/
位于尚未解压的 .war 文件中,则没有真正的路径,并且getRealPath()
将返回 null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.