2011-02-28 31 views
0

美好的一天!WEB-INF中的JPEG文件通过ServletContext返回为null#getResource()

我试图输出使用下面的代码包含在Web应用程序的 用户JPG文件:

public class JpegOutput extends HttpServlet { 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 

     byte bufferArray[] = new byte[1024]; 
     ServletContext ctxt = getServletContext(); 

     response.setContentType("image/jpeg"); 
     ServletOutputStream os = response.getOutputStream(); 
     InputStream is = ctxt.getResource("/WEB-INF/image/image1.jpg").openStream(); 
     int read = is.read(bufferArray); 
     while (read != 1) { 
      os.write(bufferArray); 
      read = is.read(bufferArray); 
     } 
     is.close(); 
     os.close(); 
    } 
} 

但出现错误:

HTTP Status 500 - 
exception java.lang.NullPointerException 

我不知道,如果它无法读取源图像或其他东西。无论如何,我把图像放在这个文件夹内/WEB-INF/image/image1.jpg

我在做什么错?我该如何解决这个问题?

编辑:我通过重命名文件名的问题解决了......文件名是大小写敏感的,而不是image1.jpg,应该image1.JPG

谢谢。

+0

是否有任何理由为什么此图像不在公共webcontent中?那么你不需要一个servlet。 – BalusC 2011-02-28 18:07:49

+0

如果你想成为一个伟大的程序员有一天(如你的个人资料所述),你真的必须回答上述评论:)这段代码味道太多了。 – BalusC 2011-03-01 14:21:18

+0

@BalusC我只是在研究可​​能性。我不打算以这种方式使用它。我只是一个初学者..我已经读了一本书,所以我试着做代码。 :) – newbie 2011-03-01 14:35:50

回答

3

您可以使用getServletContext().getRealPath("/")获取到/WEB-INF/的路径。例如。

String path = getServletContext().getRealPath("/") + "WEB-INF/image/image1.jpg"; 
InputStream is = new FileInputStream(path); 

虽然它不确定这是NPE的原因。你能检查日志文件并发布堆栈跟踪吗?

+0

'ServletContext.getResource()'不适用于类路径,它的用法是正确的。 – axtavt 2011-02-28 18:09:41

+0

真的,我的错误,与Class.getResource()混合在一起。 – morja 2011-02-28 18:36:16

0

不知道的错误,但我认为这将是更好的转发请求,而不是人工服务形象:

public class JpegOutput extends HttpServlet { 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
     request.getRequestDispatcher("/WEB-INF/image/image1.jpg") 
      .forward(request, response); 
    } 
} 

还要注意的是,你的内容,服务环是不正确,正确的长相像这样:

while ((read = is.read(bufferArray)) != -1) 
    os.write(bufferArray, 0, read); 
相关问题