关于MyEclipse Servlet中调用this.getServletContext().getRealPath()抛出异常为null的问题

问题描述:

在显示Web应用目录下图片1.png时调用new FileInputStream(this.getServletContext().getRealPath(1.png))时抛出空指针异常:

严重: Servlet.service() for servlet [downloadServlet] in context with path [/Servlet] threw exception
java.lang.NullPointerException

解决:经反复确定代码输入及路径正常后,查找到此解决方案servletContext.getRealPath(),在此阐述一下个人理解:

context.getRealPath("/")在不同的服务器上所获得的实现是不一样的,对一个打包的应用来说,是没有RealPath的概念的,调用getRealPath只会简单地返回null。其实,也很好理解,一个文件被打包入了.war文件,就不存在目录结构了(虽然包中仍然存在目录结构,但这不等同于文件系统中的目录结构)。所以,对war包中的资源是无法得到RealPath的。这样也就无从通过文件IO进行读取了。
建议:
(1)使用ServletContext.getResourceAsStream("/WEB-INF/config/aa.config")方法替代
          例如:InputStream in = this.getServletContext().getResourceAsStream("/1.jpg");
  (2)调用this.getClass().getClassLoader().getResource("/").getPath(); 获取到classes目录的全路径,在得到classes目录的全路径后再根据字符串的截取与拼装达到你的要求即可。
           例如:InputStream in =new FileInputStream(this.getClass().getClassLoader().getResource("../../1.jpg").getPath());
posted @ 2014-11-17 11:53  Eudora_Do  阅读(3764)  评论(0编辑  收藏  举报