I had uploaded an image in my postgresql database, the uploading is successful. Now I want to view this image in JSP, I was able to get it into the database but I don't know how can I pass it down into the JSP in order for it to view the image.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection connect;
String userName = null;
byte[] image = null;
String imageName = null;
try {
connect = DriverManager.getConnection(databaseUrl, databaseUsername, databasePassword);
PreparedStatement select = connect.prepareStatement("SELECT username,image,image_name FROM users WHERE username = ?;");
select.setString(1, "steve");
ResultSet selectSet = select.executeQuery();
while(selectSet.next()) {
userName = selectSet.getString(1);
image = selectSet.getBytes(2);
imageName = selectSet.getString(3);
}
request.setAttribute("username", userName);
response.setContentType(getServletContext().getMimeType(imageName));
response.setContentLength(image.length);
response.getOutputStream().write(image);
} catch (SQLException e) {
e.printStackTrace();
}
}
I tried using a requestDispatcher to pass down the image into the JSP
request.getRequestDispatcher("viewImage.jsp").include(request, response);
but I encountered a IllegalStateException(getOutputStream() is already been called).
This is my JSP code
<c:out value='${requestScope.username }' />
<img src="${pageContext.request.contextPath}">
- Are there other ways to call the JSP from the servlet to pass the image?
- By setting the content type to a image mime type, would that mean that the 'username' won't be displayed because of the content type? how do I fix it?
I had been looking for this post since morning, and I'm lost on how it was able to pass down the image into the JSP How to retrieve and display images from a database in a JSP page?
EDIT: The purpose of the application is to view a user's profile (image and text information)