database 从数据库中检索图像并使用 JSTL 将其显示在 JSP 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25051022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve images from database and display it in JSP using JSTL
提问by user3819470
Assume that when a user accesses to my website, then he will see a lot of images which have stored in the database before. I know how to do that in JSP Scriptlet, and I also know how to fetch and retrieve data from the database in JSTL when the user submit a form by using servlet. But I don't know how to do it in JSTL without user submitting a form.
假设当用户访问我的网站时,他会看到很多以前存储在数据库中的图像。我知道如何在 JSP Scriptlet 中执行此操作,并且我还知道当用户使用 servlet 提交表单时如何在 JSTL 中从数据库中获取和检索数据。但是我不知道如何在没有用户提交表单的情况下在 JSTL 中做到这一点。
回答by Braj
Yes, You can use JSTL& EL. For database access use JSTL SQL Tag library.
是的,您可以使用JSTL和EL。对于数据库访问使用 JSTL SQL 标记库。
How to display images in JSP that is stored in database?
如何在存储在数据库中的 JSP 中显示图像?
I hope you are using BLOB
type column to store images in database. Simply hit a Servlet passing id of the records and send byte[]
in response.
我希望您使用BLOB
类型列将图像存储在数据库中。只需点击一个传递记录 ID 的 Servlet 并发送byte[]
响应。
I have created separate request for each image for better user experience as well.
为了更好的用户体验,我为每个图像创建了单独的请求。
Note:It's better to move the database code in the Servlet.
注意:最好在Servlet中移动数据库代码。
JSP:
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):
小服务程序(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:
网页.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>
Table structure: (users)
表结构:(用户)
+----------+-------------+------+-----+---------+-------+
| 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 | |
+----------+-------------+------+-----+---------+-------+
回答by Vicky
If your question is about displaying database content on JSP page using JSTL tags and if you are using native style JDBC database connection (not jpa or hibernate), take a look:
如果您的问题是关于使用 JSTL 标记在 JSP 页面上显示数据库内容,并且您使用的是本机样式的 JDBC 数据库连接(不是 jpa 或 hibernate),请查看:
// make a class for you database table mapping
// assume you have id,name,salary in employee database table , make a Java class for it
class Employee{
int id;
String name;
float salary;
// now getter setter for fields
public int getId(){
return this.id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return this.name;
}
public void setName(String name){
this.name = name;
}
public float getSalary(){
return this.salary;
}
public void setSalary(int salary){
this.salary = salary;
}
}
// now in your servlet class make a list of Employee class and set data from data base
List<Employee> empList = new ArrayList<Employee>();
// asume your db connection and query is here
ResultSet rs = your_result_Set
while(rs.next()){
Employee emp = new Employee();
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
em.setSalary(rs.getFloat("slary"));
empList.add(em);
}
request.setAttribute("empList",empList);
request.getRequestDispacher("your_jsp_path").forward(request,response);
// now in your jsp add <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> on top of jsp
<table>
<c:forEach items="${empList}" var="e" >
<tr>
<td>${e.id}</td>
<td>${e.name}</td>
<td>${e.salary}</td>
</tr>
</c:forEach>
</table>
Custom MVC using servlet and jsp. Take a look using servlet 3.0 or higher
使用 servlet 和 jsp 的自定义 MVC。使用 servlet 3.0 或更高版本查看
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="login", urlPatterns={"/login"})
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try{
// do your login logic here
request.setAttribute("message","login failed");
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
}
catch(Exception exp){
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
}
// now in login.jsp placed in WEB-INF/jsp
<span>${message}</span><!-- message is request attribute here assigned in servlet-->
Now whenever you call login url request 1st comes to login servlet after that transferred to jsp
现在,每当您调用登录 url 请求时,第 1 个登录 servlet 会在转移到 jsp 之后