使用Struts 2从MySQL查看JSP页面中的图像

时间:2014-12-07 12:09:23

标签: java mysql image jsp struts2

我有一个按钮来拾取图像并将其放入MySQL数据库中。在此之后,我希望图像将显示在同一页面中。我是Struts2的新手,我现在不知道该怎么做。

这是我的班级Registrazione.java

public String visualizzaimg() throws SQLException, IOException {
    Connessione();    // DB connection method
    PreparedStatement pstmt = con.prepareStatement("SELECT Immagine FROM Utenti WHERE Username = ?");
    pstmt.setString(1,username);
    ResultSet rs = pstmt.executeQuery();
    while(rs.next()){
    fin = rs.getBinaryStream("Immagine");
    byte[] b = new byte[fin.available()];
    fin.read(b);
    }
    return "success";
}

这是我的struts.xml文件:

<action name="visualizzaimg" class="Model.Registrazione" method="visualizzaimg">
<result name="success" type="stream">
        <param name="contentType">image/jpeg</param>
        <param name="inputName">fin</param>
        <param name="contentDisposition">attachment;filename=${fileName}</param> /* Not sure if i've understood what i have to put here.. */
        <param name="bufferSize">1024</param>
    </result>
</action>

这是我的LoginRiuscito.jsp页面:

<s:form action="carica" id="carica" style="display:none" enctype="multipart/form-data">
    <s:textfield id="username" name="username" type="hidden"></s:textfield>
    <s:file id="carica" name="caricaimg" accept="image/*"></s:file>
    <s:submit value="Carica" ></s:submit>
</s:form>
<s:form action="visualizzaimg" enctype="multipart/form-data">
    <s:textfield id="username" name="username" type="hidden"></s:textfield>
    <img src="">  //i don't know what i have to put in src..
    <s:submit value="Visualizza"></s:submit>
</s:form>

1 个答案:

答案 0 :(得分:1)

重点是将网址写入<img>标记。该网址应该映射将数据流式传输到响应的操作。

<img src="<s:url action='visualizzaimg'/>">  

该操作需要返回stream结果,为此目的,它应该为InputStream提供一个getter。输入流的默认输入名称是inputStream,因此我们将使用它。

private InputStream inputStream;

public ImputStream getInputStream(){
  return inputStream;
}

public String visualizzaimg() throws SQLException, IOException {
    Connessione();    // DB connection method
    PreparedStatement pstmt = con.prepareStatement("SELECT Immagine FROM Utenti WHERE Username = ?");
    pstmt.setString(1,username);
    ResultSet rs = pstmt.executeQuery();
    if(rs.next()){
      inputStream = rs.getBinaryStream(1);
    }
    return "success";
}

现在配置结果

<result name="success" type="stream">
   <param name="contentType">image/jpeg</param>
</result>