问题描述
是的,您可以使用JSTL&EL。对于数据库访问,请使用JSTLSQL标记库。
如何在存储在数据库中的JSP中显示图像?
我希望您使用BLOB
类型列将图像存储在数据库中。只需点击传递记录ID的Servlet,然后发送byte[]
响应即可。
我还为每个图像创建了单独的请求,以提供更好的用户体验。
最好在Servlet中移动数据库代码。
JSP:
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<sql:setDataSource var="webappDataSource"
driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test"
user="root" password="root" />
<sql:query dataSource="${webappDataSource}"
sql="select id,username from users" var="result" />
<table width="100%" border="1">
<c:forEach var="row" items="${result.rows}">
<tr>
<td>${row.id}</td>
<td>${row.username}</td>
<td>
<img src="${pageContext.servletContext.contextPath }/photoServlet?id=${row.id}" />
</td>
</tr>
</c:forEach>
</table>
Servlet(PhotoServlet.java):
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost:3306/test";
final String User = "root";
final String Password = "root";
try {
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL, User, Password);
PreparedStatement stmt = conn.prepareStatement("select photo from users where id=?");
stmt.setLong(1, Long.valueOf(request.getParameter("id")));
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
response.getOutputStream().write(rs.getBytes("photo"));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
web.xml:
<servlet>
<servlet-name>PhotoServlet</servlet-name>
<servlet-class>com.server.servlet.PhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PhotoServlet</servlet-name>
<url-pattern>/photoServlet</url-pattern>
</servlet-mapping>
表结构:(用户)
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| username | varchar(30) | YES | | NULL | |
| password | varchar(20) | YES | | NULL | |
| photo | blob | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
解决方法
假设当用户访问我的网站时,他将看到很多以前存储在数据库中的图像。我知道如何在JSP
Scriptlet中做到这一点,也知道当用户使用Servlet提交表单时如何从JSTL中的数据库中获取和检索数据。但是我不知道如何在不提交用户表单的情况下在JSTL中做到这一点。