是的,您可以使用JSTL&EL。对于数据库访问,请使用JSTL
SQL标记库。
如何在存储在数据库中的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 | |+----------+-------------+------+-----+---------+-------+



