P粉2519031632023-08-28 18:47:50
Let’s step by step and see what happens:
element. src
attribute. src
attribute needs to point to a valid http://
URL, so not a local disk file system path file://
because when the server and client This will never work when running on a physically different machine. http://example.com/context/images/foo.png
) or as a request parameter (e.g. http:/ /example.com/context/images?id=1
). /images/*
, so you can execute some Java code on a specific URL. byte[]
or InputStream
, JDBC API provides ResultSet #getBytes()
and ResultSet#getBinaryStream()
< /a> For this purpose, JPA API provides @Lob
to this end. 李>
byte[]
or InputStream
to the response's OutputStream
(the usual Java IO Way.Content-Type
response header needs to be set as well. You can do this via ServletContext#getMimeType()
Based on the image file extension, you can do this via the extension in
web.xml and/or Override this extension
. This should be. It pretty much writes the code itself. Let's start with HTML (in 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">
If needed, you can also set it dynamically using EL src
="https://stackoverflow.com/tags/jstl/info">JSTL:
<c:forEach items="${imagenames}" var="imagename">
<img src="${pageContext.request.contextPath}/images/${imagename}">
</c:forEach>
Then define/create a servlet that listens on /images/*< URL 模式上的 GET 请求/code>, the following example uses plain JDBC to do the job:
@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); } } }
That's it. If you are worried about HEAD and cache headers and responding to these requests correctly, use this Abstract Template for a Static Resource servlet.