Servlet doGet() code for getting an Image from Database and to store image in Response
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// Get userid from session
try {
// Get photos from database in (image)
// Init servlet response.
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(image.getContenttype());
response.setHeader("Content-Length", String.valueOf(image.getLength()));
response.setHeader("Content-Disposition", "inline; filename=\"" + image.getTitle()
+ "\"");
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams.
input = new BufferedInputStream(image.getPhoto(), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(),
DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
// Gently close streams.
output.close();
input.close();
}
//Redirect it to photo page
RequestDispatcher rd = request.getRequestDispatcher
("/webplugin/jsp/profile/photos.jsp");
rd.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
However, When this servlet shows the JSP page it shows only image and not the JSP page.
JSP code:
... JSP code
<img src="Servlet url">
... JSP code cont...
What output I get:
- I only get Image instead of image inside JSP
- When I use RequestDispatcher/sendRedirect() I get following Exception
java.lang.IllegalStateException: Cannot forward after response has been committed
Question:
- How to get Image inside JSP instead of just Image in browser
- How to avoid above Exception?
EDIT: My Web.xml looks like this
<servlet>
<servlet-name>Photo Module</servlet-name>
<servlet-class>app.controllers.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Photo Module</servlet-name>
<url-pattern>/Photos</url-pattern>
</servlet-mapping>
Enter the URL to the JSP file containing the
<img>element in the browser address bar.Remove the following lines from the servlet code.
The servlet should just return the image. Nothing more. It’s the webbrowser itself who is supposed to download and display the image, not the webserver.
See also: