如何直接将blob类型打印到jsp

时间:2013-10-10 05:00:32

标签: jsp blob

我正在使用jquerymobile + jsp

制作应用

结构与普通的servlet-jsp MVC不同。

它直接获取数据并将其打印出来,

<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.io.*"%>

<%! Connection con=null; %>
<%! Statement st= null; %>



<% 
try {
ResultSet rs= null; 
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/first_app";
String user = "root";
String password = "test"; 
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, user, password);
try {
    String sql = "SELECT * FROM lunch_menu";
        PreparedStatement ps = con.prepareStatement(sql);
        rs = ps.executeQuery();

%>


<div data-role="page">
    <div data-role="header">
        <h1>MENU PAGE</h1>
    <a href="#" data-rel="back" data-icon="arrow-l">Back</a>
</div>

<div data-role="content">
    <ul data-role="listview">
        <!--
        <li><img src="/FirstApp/assets/img/1.jpg" />2013-10-08 똥맛카레</li>
        <li><img src="/FirstApp/assets/img/2.jpg" />2013-10-08 카레맛똥</li>
        -->
        <%

        while(rs.next()){
        Blob image = null;
        image = rs.getBlob("lunch_image");
        out.print("<li>");
            //prints com.mysql.jdbc.Blob@2d58497c
            out.print(rs.getBlob("lunch_image"));
            //prints [B@686fdca5
            //out.print(image.getBytes(1,(int)image.length()));


            out.print("</li>");
        }
        } catch (SQLException e) {
        e.printStackTrace();
        }
        }catch(ClassNotFoundException ce){out.println(ce);}
        %>


        </ul>
    </div>


</div>

就像我评论的那样,

我已经检查过blob类型数据是否存在,但我不知道如何显示数据。如果这是jsp-servlet,我知道我必须这样做。

InputStream in = image.getBinaryStream();
int length = (int) image.length();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}

但我不喜欢这种情况。

1 个答案:

答案 0 :(得分:1)

您无法直接将blob类型打印到html(jsp)代码中。这将永远不会像你尝试这样做。

我建议创建一个输出图像的servlet。请参阅此处如何执行此操作How to retrieve image from database and display in JSP via Servlet?。然后在您的代码中调用servlet就像这样:

<img src='path_to_servlet/ServletName?imageId=xxx'>