我试图从oracle sql数据库中获取所有图像,但每次都会显示一个图像。 我正在使用会话变量来传输行的uuid。
简化示例:
JSP代码:
HttpSession ses2=request.getSession();
Connection cn3;
PreparedStatement ps3;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn3=DriverManager.getConnection("jdbc:odbc:sm","system","gecbsp");
ps3=cn3.prepareStatement("select * from sm_post order by time DESC");
ResultSet rs5=ps3.executeQuery();
while(rs5.next())
{
String puid = rs5.getString("post_uuid");
ses2.setAttribute("ses_puid",puid);
out.println("<img src = './post_pic' width = '400px' height = '300px' border = '2' align = 'middle' name = '"+puid+"'/>");
}
}
catch(Exception ee)
{
ee.printStackTrace();
}
图片Servlet:
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class post_pic extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession ses2=request.getSession();
String puid = (String)ses2.getAttribute("ses_puid");
String imgLen="";
Connection cn;
PreparedStatement ps;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn=DriverManager.getConnection("jdbc:odbc:sm","system","gecbsp");
ps=cn.prepareStatement("select post_image from sm_post where post_uuid = ?");
ps.setString(1,puid);
ResultSet rs = ps.executeQuery();
if(rs.next()){
imgLen = rs.getString(1);
System.out.println(imgLen.length());
}
ps=cn.prepareStatement("select post_image from sm_post where post_uuid = ?");
ps.setString(1,puid);
ResultSet rs2 = ps.executeQuery();
if(rs2.next()){
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs2.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
System.out.println("index"+index);
ps.close();
cn.close();
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
}
catch (Exception e){
e.printStackTrace();
}
ses2.setAttribute("ses_puid", puid);
}
}
我的数据库中有5个图片,但在每个img src标记中,它显示了最新插入的图片。
答案 0 :(得分:0)
您在循环中覆盖会话属性:
ses2.setAttribute("ses_puid",puid);
尝试使用请求参数而不是会话属性:
<强> JSP:强>
out.println("<img src = './post_pic?puid="+puid+"' width = '400px' height = '300px' border = '2' align = 'middle' name = '"+puid+"'/>");
<强>的Servlet 强>
String puid = request.getParameter("puid");
答案 1 :(得分:0)
List<String> images = new ArrayList<String>();
while (rs5.next()) {
String puid = rs5.getString("post_uuid");
images.add(puid);
}
ses2.setAttribute("ses_puid", images);
并使用JSP中的图像列表