2014-06-21 61 views
1

這是我的代碼。我有數據庫中的文件夾和文件路徑中的圖像我想檢索所有圖像的最後創建的行我的意思是我想顯示第一個最後的圖像。如何顯示圖像最後在jsp數據庫中創建

<%@ include file="getcon.jsp"%> 
<html> 
<head> 
<title>View Image Page</title> 
</head> 
<body> 
<table width="100%" border="0"> 
<!-- main content --> 
<% 
String type=request.getParameter("type"); 
String sql; 

if(type!=null) 
     { 
    sql="SELECT PICTURE, TITLE, TAG, POST from testimage where type='"+type+"'"; 




ResultSet rs=null; 
try 
{ 

rs=st.executeQuery(sql); 


while(rs.next()) 
{ 
%> 
<table width="700%" height="600" border="1" align="center"> 
<tr> 
<!-- Mention Directory where your images has been saved--> 
<% String filename=rs.getString(2); 

            //System.out.println("filename isssssss"+filename); 
            out.println("<b>"+filename+"</b>"); 
            out.println(application.getRealPath("/")); 
            //session.setAttribute("download",filename); 
          %> 

<td><img src="jokeimage\<%=rs.getString(1)%>" width="500" height="400" /></td> 
</tr> 
</table> 
<% 
} 
} 
catch(Exception e) 
{ 
out.print(""+e.getMessage()); 
} 
} 
else{} 
%> 
+1

請儘量避免* Scriplet *代替使用JSTL&EL。 – Braj

+0

確切的問題在哪裏?在從服務器訪問數據庫或圖像時,請詳細解釋一下? – Braj

回答

0

我會選擇一個PreparedStatement和綁定參數(因爲當前查詢是易受SQL Injection),假設對於每個連續行的POST列值增大;它可能做這樣的事情在controller Servlet -

sql="SELECT PICTURE, TITLE, TAG, POST from testimage where type=? ORDER BY POST DESC"; 
PreparedStatement ps = null; 
try { 
    ps = conn.prepareStatement(sql); 
    ps.setString(1, type); 
    rs = ps.executeQuery(); 
    // ... Read the ResultSet ... 
} finally { 
    try { 
    rs.close(); 
    } catch (Exception ignored) { 
    } 
    try { 
    ps.close(); 
    } catch (Exception ignored) { 
    } 
} 
0

總是儘量避免Scriplet元素改用JSP Standard Tag Library是更易於使用和不容易出錯

您可以使用專爲在JSP中訪問數據庫而設計的SQL Tag Library

示例代碼:(更改數據庫URL和憑據

<%@ 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="dataSource" driver="com.mysql.jdbc.Driver" 
    url="jdbc:mysql://localhost:3306/db" user="root" password="" /> 

<sql:query dataSource="${dataSource}" sql="SELECT PICTURE, TITLE from testimage where type=? ORDER BY CREATION_DATE DESC" var="result"> 
    <sql:param value="${param.type}"/> 
</sql:query> 

<table width="100%" height="600" border="1" align="center"> 
    <c:forEach var="row" items="${result.rows}"> 
     <tr> 
      <td><b>${row.tag}</b></td> 
      <td><img src="${pageContext.request.contextPath}/jokeimage/${row.picture}" width="500" height="400" /></td> 
     </tr> 
    </c:forEach> 
</table> 

我怎麼轉換成JSTL & EL從Scriplet?

  1. ${param.type}用於request.getParameter("type")
  2. ${pageContext.request.contextPath}用於application.getRealPath("/")
  3. c:forEach標記用於while循環
  4. sql:param用於參數化查詢
  5. sql:setDataSource用於創建數據源
  6. sql:query用於執行查詢
相關問題