如何在JSP页面中从数据库检索和显示图像?
让我们逐步查看会发生什么:
<img>
src
http://
file://
http://example.com/context/images/foo.png
http://example.com/context/images?id=1
/images/*
byte[]
InputStream
ResultSet#getBytes()
ResultSet#getBinaryStream()
InputStreamOutputStream
ServletContext#getMimeType()
<mime-mapping>
web.xml
应该是这样。它几乎自己编写代码。让我们从HTML(在JSP中)开始:
<img src="${pageContext.request.contextPath}/images/foo.png"> <img src="${pageContext.request.contextPath}/images/bar.png"> <img src="${pageContext.request.contextPath}/images/baz.png">
必要时,可以动态地也设置src有EL而使用迭代JSTL:
<c:forEach items="${imagenames}" var="imagename"> <img src="${pageContext.request.contextPath}/images/${imagename}"> </c:forEach>
然后定义/创建一个servlet,该servlet侦听URL模式为的GET请求/images/*,以下示例将普通的JDBC用于作业:
@WebServlet("/images/*") public class ImageServlet extends HttpServlet { // content=blob, name=varchar(255) UNIQUE. private static final String SQL_FIND = "SELECT content FROM Image WHERE name = ?"; @Resource(name="jdbc/yourDB") // For Tomcat, define as <Resource> in context.xml and declare as <resource-ref> in web.xml. private DataSource dataSource; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String imageName = request.getPathInfo().substring(1); // Returns "foo.png". try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_FIND)) { statement.setString(1, imageName); try (ResultSet resultSet = statement.executeQuery()) { if (resultSet.next()) { byte[] content = resultSet.getBytes("content"); response.setContentType(getServletContext().getMimeType(imageName)); response.setContentLength(content.length); response.getOutputStream().write(content); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404. } } } catch (SQLException e) { throw new ServletException("Something failed at SQL/DB level.", e); } } }