Reputation: 827
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:
java.lang.IllegalStateException: Cannot forward after response has been committed
Question:
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>
Upvotes: 0
Views: 13536
Reputation: 240860
1 you are modifying response and then forwarding , it is useless. don't do it.
2 How to get image from servlet to jsp
Upvotes: 2
Reputation: 1108632
How to get Image inside JSP instead of just Image in browser
Enter the URL to the JSP file containing the <img>
element in the browser address bar.
http://localhost:8080/contextname/webplugin/jsp/profile/photos.jsp
How to avoid above Exception?
Remove the following lines from the servlet code.
//Redirect it to profile page
RequestDispatcher rd = request.getRequestDispatcher
("/webplugin/jsp/profile/photos.jsp");
rd.forward(request, response);
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.
Upvotes: 4