java 尽管使用 servletContext(),但 getResourceAsStream 返回 null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14997523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:08:49  来源:igfitidea点击:

getResourceAsStream returns null inspite of using servletContext()

javafileservlets

提问by Vishal Anand

This is a servlet that reads a .pdf and sends it as response. I don't understand why is it not working.

这是一个读取 .pdf 并将其作为响应发送的 servlet。我不明白为什么它不起作用。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/pdf");
        ServletContext sc = this.getServletContext();
        String path = sc.getRealPath("/WEB-INF/pdf/order.pdf");
        System.out.print(path);// this prints correct path
        InputStream is = null;
        try{
            is = sc.getResourceAsStream(path); // this is not working
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.print(is);// it is null
        int read = 0;
        byte[] bytes = new byte[2048];
        OutputStream os = response.getOutputStream();

        try{
        while((read = is.read(bytes))!= -1){  //exception is thrown here
            os.write(bytes,0,read);
        }
        }catch(Exception e){
            e.printStackTrace();
        }
        os.flush();
        os.close();
      }

Can anyone explain why is it not working, ispite of using this.getServletContext().getRealPath("/WEB-INF/pdf/demo.pdf");

任何人都可以解释为什么它不起作用,尽管使用 this.getServletContext().getRealPath("/WEB-INF/pdf/demo.pdf");

here is the stack trace:

这是堆栈跟踪:

2/21/13 14:24:21:322 IST] 00000033 SystemErr     R java.lang.NullPointerException
[2/21/13 14:24:21:323 IST] 00000033 SystemErr     R     at com.tgmc.servlets.DisplayOrder_PDF_Servlet.doGet(DisplayOrder_PDF_Servlet.java:42)
[2/21/13 14:24:21:323 IST] 00000033 SystemErr     R     at javax.servlet.http.HttpServlet.service(HttpServlet.java:718)
[2/21/13 14:24:21:323 IST] 00000033 SystemErr     R     at javax.servlet.http.HttpServlet.service(HttpServlet.java:831)
[2/21/13 14:24:21:323 IST] 00000033 SystemErr     R     at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1449)
[2/21/13 14:24:21:323 IST] 00000033 SystemErr     R     at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:790)
[2/21/13 14:24:21:323 IST] 00000033 SystemErr     R     at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:443)
[2/21/13 14:24:21:323 IST] 00000033 SystemErr     R     at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:175)
[2/21/13 14:24:21:323 IST] 00000033 SystemErr     R     at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3610)
[2/21/13 14:24:21:323 IST] 00000033 SystemErr     R     at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:274)
[2/21/13 14:24:21:324 IST] 00000033 SystemErr     R     at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:926)
[2/21/13 14:24:21:324 IST] 00000033 SystemErr     R     at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1557)
[2/21/13 14:24:21:324 IST] 00000033 SystemErr     R     at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:173)
[2/21/13 14:24:21:324 IST] 00000033 SystemErr     R     at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:455)
[2/21/13 14:24:21:324 IST] 00000033 SystemErr     R     at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewInformation(HttpInboundLink.java:384)
[2/21/13 14:24:21:324 IST] 00000033 SystemErr     R     at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:288)
[2/21/13 14:24:21:324 IST] 00000033 SystemErr     R     at com.ibm.ws.ssl.channel.impl.SSLConnectionLink.determineNextChannel(SSLConnectionLink.java:1016)
[2/21/13 14:24:21:324 IST] 00000033 SystemErr     R     at com.ibm.ws.ssl.channel.impl.SSLConnectionLink$MyReadCompletedCallback.complete(SSLConnectionLink.java:639)
[2/21/13 14:24:21:324 IST] 00000033 SystemErr     R     at com.ibm.ws.ssl.channel.impl.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1772)
[2/21/13 14:24:21:324 IST] 00000033 SystemErr     R     at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
[2/21/13 14:24:21:324 IST] 00000033 SystemErr     R     at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
[2/21/13 14:24:21:325 IST] 00000033 SystemErr     R     at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
[2/21/13 14:24:21:325 IST] 00000033 SystemErr     R     at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
[2/21/13 14:24:21:325 IST] 00000033 SystemErr     R     at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:202)
[2/21/13 14:24:21:325 IST] 00000033 SystemErr     R     at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:766)
[2/21/13 14:24:21:325 IST] 00000033 SystemErr     R     at com.ibm.io.async.ResultHandler.run(ResultHandler.java:896)
[2/21/13 14:24:21:325 IST] 00000033 SystemErr     R     at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1527)

回答by vikingsteve

Did you try sc.getResourceAsStream("/WEB-INF/pdf/order.pdf")

你试过 sc.getResourceAsStream("/WEB-INF/pdf/order.pdf")

and is it located under src/main/resources/WEB-INF/pdf ? file named .pdf and not .PDF?

它是否位于 src/main/resources/WEB-INF/pdf 下?名为 .pdf 而不是 .PDF 的文件?

edit: I tried this at home and it works for me.

编辑:我在家里试过这个,它对我有用。

    try{
        is = sc.getResourceAsStream("/WEB-INF/pdf/order.pdf"); // this works!
    }catch(Exception e){
        e.printStackTrace();
    }

Note: give you have a standard build, order.pdf should be in src/main/webapp/WEB-INF/pdf folder

注意:给你一个标准版本,order.pdf 应该在 src/main/ webapp/WEB-INF/pdf 文件夹中

(rather than src/main/resources...).

(而不是 src/main/resources...)。

Vishal, can you give this another try using my code above and checking the folder structure?

Vishal,您能否使用我上面的代码再试一次并检查文件夹结构?

回答by Tony Vu

I had the NullPointerException when calling GetResourceAsStream() on ServletContext too and have fixed so I post here for those who encounter the same issue. According to the document at http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html, the method getRealPath() will return the real path on the server filesystem, so calling sc.getRealPath("/WEB-INF/pdf/order.pdf")as the code above will probably return /opt/apache-tomcat/wtpwebap??ps/itext/WEB-INF/pdf/order.pdfassuming /opt/apache-tomcat/ is the location of your tomcat on the server. The document also mentions that for the method getResourceAsStream(), we should pass in the relative path to the servlet context root starting with /. So for the code above, you should pass /WEB-INF/pdf/order.pdfinsead of the real path to getResourceAsStream() method.

在 ServletContext 上调用 GetResourceAsStream() 时,我也遇到了 NullPointerException 并已修复,因此我在此处为遇到相同问题的人发帖。根据http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html上的文档, getRealPath() 方法将返回服务器文件系统上的真实路径,因此调用sc.getRealPath("/WEB-INF/pdf/order.pdf")上面的代码/opt/apache-tomcat/wtpwebap??ps/itext/WEB-INF/pdf/order.pdf假设 /opt/apache-tomcat/ 是您的 tomcat 在服务器上的位置,可能会返回。该文档还提到,对于 getResourceAsStream() 方法,我们应该传入以 / 开头的 servlet 上下文根的相对路径。因此,对于上面的代码,您应该将/WEB-INF/pdf/order.pdf真实路径的 insead传递给 getResourceAsStream() 方法。

sc.getResourceAsStream("/WEB-INF/pdf/order.pdf")