从数据库检索图像,并使用JSTL在JSP中显示它

【字号: 日期:2024-03-30浏览:35作者:雯心
(adsbygoogle = window.adsbygoogle || []).push({}); 如何解决从数据库检索图像,并使用JSTL在JSP中显示它?

是的,您可以使用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 border='1'> <c:forEach var='row' items='${result.rows}'><tr> <td>${row.id}</td> <td>${row.username}</td> <td> <img src='https://www.6hehe.com/wenda/${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 | |+----------+-------------+------+-----+---------+-------+解决方法

假设当用户访问我的网站时,他将看到很多以前存储在数据库中的图像。我知道如何在JSPScriptlet中做到这一点,也知道当用户使用Servlet提交表单时如何从JSTL中的数据库中获取和检索数据。但是我不知道如何在不提交用户表单的情况下在JSTL中做到这一点。

相关文章: