好吧,遗憾的是我什至不知道如何描述这个错误哈哈:(
我想显示我已将其路径存储在数据库中的图像。我的代码第一次访问数据库时工作得很好。但是,我的代码第二次访问数据库时检索到 null,依此类推。我盯着我的代码看了几个小时,但找不到错误,哈哈:(
getimage.jsp
<form action="getimage" method="get">
<input type="text">
<input type="submit" name="getimage">
</form>
<c:forEach var="image" items="${image_path}">
<img src="${image}"/>
</c:forEach>
servlet:
HttpSession session = request.getSession();
session.removeAttribute("image_path");
List<String> list_image_path = new ArrayList<String>();
ImagePath img = ImageDao.getInstance().getPath(8);
list_image_path.add(img.getImagePath());
session.setAttribute("image_path", list_image_path);
System.out.println(img);
request.getRequestDispatcher("getimage.jsp").forward(request, response);
ImageDao.java
private ImageDao() {
try {
conn = MyDatabase.getConnection();
} catch (SQLException e) {
System.out.println( e.getClass() + " - Can not connect to the databse");
e.printStackTrace();
}
}
public static ImageDao getInstance() {
if(instance == null) {
synchronized( UsersDao.class) {
if( instance == null ){
instance = new ImageDao();
}
}
}
return instance;
}
public static ImagePath getPath( long id) {
ImagePath path = new ImagePath();
String sql = "SELECT * FROM item_image WHERE id=?";
try {
System.out.println(id + ": " + conn);
PreparedStatement pstmt = conn.prepareStatement( sql );
pstmt.setLong(1, id);
ResultSet rs = pstmt.executeQuery(); // Fail right here
if( rs.next() ) {
System.out.println( rs.getLong("id") + ": " + rs.getString("path") + " " + id);
path.setId( rs.getLong( "id" ));
path.setImagePath( rs.getString("path"));
}
pstmt.close();
rs.close();
conn.close();
return path;
} catch( SQLException e ) {
System.out.println("Cant get it");
} finally {
if( conn != null ) { try { conn.close(); } catch( SQLException e) {}};
}
return path;
}
这是我嵌入 ImageDao.java 的控制台上显示的消息: 首次访问:
8: org.postgresql.jdbc4.Jdbc4Connection@3d3cdc3b
8: upload/download.jpg 8
Id: 8 path: upload/download.jpg
第二次访问:
8: org.postgresql.jdbc4.Jdbc4Connection@3d3cdc3b
Cant get it
Id: 0 path: null
最佳答案
您仅在单例构造函数中创建连接一次,并在第一个查询结束时关闭它。
然后,在第二个查询中,连接关闭,您无法执行查询。
在查询之前创建连接。
关于java - 第二次访问时为空数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25151693/