1

I have a servlet, Starter.java, in whose doGet() method I use a PrinterWriter object to print HTML.

I have an image file: C:/.../Entertainment_mgmt/src/images/logo.png (inside my project), which I would like to display a Servlet page which I fetch from my localhost, at localhost:8084/Starter. The page also has other HTML structures, which I would like to retain (that is, I would like to fit the image in a on a small section of the screen). Simply outputting <img src="C:/.../Entertainment_mgmt/src/images/logo.png" /> to HTML does not seem to work.

I've not performed any manual servlet mapping and I haven't changed any of Tomcat's configuration files.

enter image description here

I have checked many similar posts, but I just can't seem to get a hang of it.

EDIT: I see that this post has been marked as a duplicate. I feel that this post still has significance due to the simple fact that other programmers might make the same mistake I did (regarding Tomcat serving images along with pages). Moreover, this provides a solution that does not require changing of Tomcat's /conf/server.xml file

2
  • HTML doesn't expect paths to files. It expects http URLs pointing to images served by the HTTP server. Your images should be under "Web pages", to be served by the web server. And the HTML should contain HTTP URLs to these images, not local file paths: <img src="${pageContext.request.contextPath}/images/logo.png" />
    – JB Nizet
    Apr 2, 2016 at 15:38
  • @JBNizet: I get that now. But I was confused because almost all the browsers are able to open images from filepath directly on the hard drive (this is how many new programmers linked files when first learning HTML). I expected Tomcat to fill the gap, and serve the images along with the pages. Apr 2, 2016 at 18:35

2 Answers 2

2

Okay so I figured out the answer. It turns out that to load an image, you actually need Java code to write out the binary data via a BufferedOutputStream (being a total newbie, I had thought that Tomcat would take care of that for me).

Concretely, you need a servlet to actually convert a path like "/images/logo.jpg" in your HTML into a usable image. The servlet is called via a servlet mapping of /images/* to the servlet. By extracting the * part of /images/* , we are able to get the exact image name, and then the servlet can load it.

Here's the servlet mapping (to be added to WEB-INF/web.xml):

...
<servlet>
    <servlet-name>DisplayImage</servlet-name>
    <servlet-class>servlets.DisplayImage</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>DisplayImage</servlet-name>
    <url-pattern>/images/*</url-pattern>
</servlet-mapping>
...

Note that in my project, DisplayImage is found in C:/.../Entertainment_mgmt/src/servlets/DisplayImage.java.

Of course, you can add whatever you want in your mapping. The mapping is what is seen in the URL, as in localhost:8040/images/logo.jpg or inside an HTML page as <img src="/images/logo.jpg" />. From the point of servlets, both are the same thing. As per the mapping above, both are handled by the servlet DisplayImage.

I found some code for the DisplayImage servlet here. I've modified it a bit:

package servlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DisplayImage extends HttpServlet {
    public final String imagesBase = "F:\\Workspaces\\Java\\Projects\\Entertainment_mgmt\\src\\images/";

    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
        String URLAfterWebDomain = request.getRequestURI();

        //Only accept mappings as src="/images/whatever.jpg", even if web.xml has other mappings to this servlet.
        if(URLAfterWebDomain.startsWith("/images/") == false)   
            return;

        //get the image name, or even directory and image, e.g. /images/music/beethoven.jpg:
        String relativeImagePath = URLAfterWebDomain.substring("/images/".length());  //will get "music/beethoven.jpg"

        System.out.println("\nFetching image from "+imagesBase+relativeImagePath);
        response.setContentType("image/jpeg"); //as far as I know, this works for PNG as well. You might want to change the mapping to /images/*.jpg if it's giving problems

        ServletOutputStream outStream;
        outStream = response.getOutputStream();
        FileInputStream fin = new FileInputStream(imagesBase+relativeImagePath);

        BufferedInputStream bin = new BufferedInputStream(fin);
        BufferedOutputStream bout = new BufferedOutputStream(outStream);
        int ch =0; ;
        while((ch=bin.read())!=-1)
            bout.write(ch);

        bin.close();
        fin.close();
        bout.close();
        outStream.close();
    }
}

You can set imagesBase to any folder on your computer, it doesn't have to be in your project folder. You can also change the name of the /images/ folder to /pics/ or whatever.

Now, whenever I put an <img> tag in an HTML, I can use src="/images/whatever.jpg" attribute to call the DisplayImage servlet and show the image. That image can then be repositioned, etc.

This can even be done inside other servlets which write out HTML. In that case, the servlets are called independently and output over HTTP independently (this is why in some web pages, the text loads first and the image loads later).

0

The image path you are providing is a absolute file path. The web resources are not accessed over the normal file path over the network, they are referred by the relative path from the webapp deployed on webserver.

You can put your images folder in a webapp base folder of the webserver and access the image using localhost:8084/images/logo.png

5
  • I doesn't seem to work. Is there any servlet mapping I must implement for this to be workable? The relative path (assuming C:/.../Entertainment_mgmt is the base) becomes /src/images/logo.png, but that doesn't work either. Apr 2, 2016 at 16:43
  • how are you deploying the webapp on the server? Apr 2, 2016 at 17:35
  • Netbeans, currently. I'm using Tomcat8 and localhost Apr 2, 2016 at 17:42
  • ok, get to the tomcat webapps folder, you will find a folder for your application, locate the images folder in your application folder. Apr 2, 2016 at 17:50
  • My project is not on the webapps path, I imported it directly. Actually nevermind, I've figured out a solution. Will post a response soon. Thanks for the help though :) Apr 2, 2016 at 17:53

Not the answer you're looking for? Browse other questions tagged or ask your own question.