Good day!
I am trying to output a JPG file contained in the web application to the user using the following code:
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();
    }
}
But an error appears:
HTTP Status 500 -
exception java.lang.NullPointerException
I am not sure if it can't read the source image or something. Anyway, I put the image inside this folder /WEB-INF/image/image1.jpg
What am I doing wrong? How can I resolve this issue?
EDIT: I solved the problem by renaming the filename... the file name is case sensitive, instead of image1.jpg, it should be image1.JPG
Thank you.
You might use getServletContext().getRealPath("/") to get the path to /WEB-INF/. E.g.
String path = getServletContext().getRealPath("/") + "WEB-INF/image/image1.jpg";
InputStream is = new FileInputStream(path);
Though its not sure that this is the reason for the NPE. Can you check the log file and post the stacktrace?
Not sure about the error, but I think it would be better to forward the request rather than serve the image manually:
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);
    }
}
Also note that you content-serving loop is incorrect, the correct one looks like this:
while ((read = is.read(bufferArray)) != -1)
    os.write(bufferArray, 0, read);
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论