How to get the image from project classpath in Servlet on Netbeans

前端 未结 1 1280
执笔经年
执笔经年 2021-01-20 23:39

I made a /header folder in the web pages directory in Netbeans and added an image named header.png. Now I want to access this image file in a servlet u

相关标签:
1条回答
  • 2021-01-21 00:36

    The Class#getResource() returns an resource from the class path, not from the public web content.

    You need ServletContext#getResource(), or better, getResourceAsStream() instead.

    BufferedImage image = ImageIO.read(getServletContext().getResourceAsStream("/header/header.png"));
    

    (note that I removed the trailing space from the path as well)

    Note that some users may suggest you to use ServletContext#getRealPath(), but you shouldn't use it in this particular case as that may return null when the container is configured to expand the deployed WAR into memory instead of local disk file system.

    See also:

    • What does servletcontext.getRealPath("/") mean and when should I use it
    0 讨论(0)
提交回复
热议问题