【发布时间】:2011-09-13 00:38:50
【问题描述】:
我的 ImageDAO 如下所示:
public InputStream getPhotos(Long userid) throws
IllegalArgumentException, SQLException, ClassNotFoundException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultset = null;
Database database = new Database();
InputStream binaryStream = null;
try {
connection = database.openConnection();
preparedStatement = connection.prepareStatement(SQL_GET_PHOTO);
preparedStatement.setLong(1, userid);
preparedStatement.executeUpdate();
while(resultset.next()) {
binaryStream = resultset.getBinaryStream(4);
}
} catch (SQLException e) {
throw new SQLException(e);
} finally {
close(connection, preparedStatement, resultset);
}
return binaryStream;
}
我的 ImageServlet 看起来像这样:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Getting user id from session
HttpSession session = request.getSession(false);
Long userid = (Long) session.getAttribute("user");
try {
InputStream photoStream = imageDAO.getPhotos(userid);
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open streams
input = new BufferedInputStream(photoStream, 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 {
output.close();
input.close();
}
//Redirect it to profile page
RequestDispatcher rd = request.getRequestDispatcher
("/webplugin/jsp/profile/photos.jsp");
rd.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
我的 JSP 图片 src 应该是什么样子的
<img src="What to put here">
披露:
servlet 代码复制自此链接http://balusc.blogspot.com/2007/04/imageservlet.html
问题:
- 如何从 ImageServlet 检索 JSP 中的图像。 Stackoverflow 中有人说要放
<img src="URL to Servlet" />。但我不明白这意味着什么。 - 上述方法是从数据库中检索图像的正确方法吗?或者有没有更好的方法。
编辑:我的 Web.xml 看起来像这样
<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>
【问题讨论】: