Pages

Thursday 28 March 2013

Displaying dynamically generated images in a JSP document

My small web application contains 1 java bean - helper class (Model), 2 JSP-pages (Views), 2 servlets (Controlers). First page index.jsp contains the html form to send a request with all requested information to a servlet.

Then it transforms all incoming parameters into session attributes like that:

            HttpSession session = request.getSession(true);
            String text = "ABC abc XYZ xyz";           
            if(request.getParameter("text") != null) {
                text = request.getParameter("text");
            }
            session.setAttribute("text", text);

At the end the servlet transfers control (the thread of execution) to the final jsp-page using the RequestDispatcher:

            RequestDispatcher dispatcher = 
                getServletContext().getRequestDispatcher("/answer.jsp");
            dispatcher.forward(request, response);

The final JSP-page contains only HTML IMG tag: <img src = "ImageDispatcher" /> and src has a link to the servlet which produces an image:
When the browser sees the a html img tag it makes a new request to the server via the link provided to the ImageDispatcher servlet. Using forwarded attributes the servlet instantiates and initializes ImageGenerator (Render) Class which produces the BufferedImage object. And then the servlet returns the final image:

            response.setContentType("image/png");
            OutputStream outStream = response.getOutputStream();
                            // output the image as png
            ImageIO.write(bufferImg, "png", outStream); 
            outStream.flush();
            outStream.close();

No comments:

Post a Comment