Pass dynamic image to JSP with servlet

10,799

You need to understand that it's the webbrowser who has got to download the invididual images based on the URLs of the <img> elements found in the retrieved HTML code and that it's not the webserver who has got to inline the image's raw content in the produced HTML code somehow.

You really need to create a standalone image servlet for this which listens on those specific URLs of the <img> elements. You can make the servlet reuseable by providing an unique image idenfitier in the request query string or request path info during generating the HTML code.

E.g.

<img src="imageServlet?param1=value1&param2=value2" />

with a

@WebServlet("/imageServlet")
public class ImageServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Create image based on request.getParameter() information.
        // Set proper content type by response.setContentType().
        // Write image to response.getOutputStream().
    }

}

See also:

Share:
10,799
cafman
Author by

cafman

Updated on June 15, 2022

Comments

  • cafman
    cafman almost 2 years

    I have a desktop app that creates a graphics 2D object, sticks it in a panel and draws it. I am trying to convert this app to a webpage using servlets and jsps. I have been reading online for 2 days and can't wrap my head around how to do this, each example I find seems to leave out an important piece. I don't want to save the image to file because each user will get a new/different image.

    Can I create the image in the servlet along with the other response variables and pass them to the jsp at the same time? Then call the image using something like ${response.image}.This seems be preferable but doesn't seem to work.

    Or do I need a separate servlet just for the image (this seems harder)? Also how do I prepare the Graphics2D object to be used as an image in HTML?

  • cafman
    cafman almost 12 years
    Thanks, this helped me understand.