Pass dynamic image to JSP with servlet

后端 未结 2 1681
面向向阳花
面向向阳花 2021-01-22 03:14

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 read

相关标签:
2条回答
  • 2021-01-22 03:25

    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:

    • How to retrieve and display images from a database in a JSP page? - follows a similiar approach
    0 讨论(0)
  • 2021-01-22 03:40

    I'll just answer on the first part of the question. To embed an image into an HTML page, you first need to generate the HTML page which will contain the following markup:

    <img src="somePath" />
    

    This HTML markup will be sent in the response to the request, and the browser will parse it. It will then send a second HTTP request to somePath, to download the bytes of the image.

    So, you need to somehow store the generated image in memory and wait for the second request, and then send the bytes to the response, or you need to delay the image generation until the second request comes in. I much prefer the second solution. So the goal of the code handling the first request will just be to generate markup containing an img tag pointing to an appropriate URL. This URL should contain all the parameters necessary to actually generate the image.

    For the second part, you will certainly have to create a BufferedImage instance, draw to its Graphics2D object, and use ImageIO to write this BufferedImage to the response output stream.

    0 讨论(0)
提交回复
热议问题