无法使用hibernate和struts在数据库中显示jsp中的图像

时间:2014-07-18 05:08:33

标签: java hibernate jsp struts2

我正在尝试从数据库获取图像,我能够获取图像,现在我想将该图像显示到jsp页面。我正在使用hibernate和struts。我有一个动作类和一个hibernate持久化类(POJO)。

动作类是SportsAction

package action;

@Result(location="sports-success.jsp")
public class SportsAction extends ActionSupport{

public List<SportsSetterAndGetter> l;

public List<SportsSetterAndGetter> getL() {
    return l;
}

public void setL(List<SportsSetterAndGetter> l) {
    this.l = l;
}

private byte[] pic;

public byte[] getPic() {
    return pic;
}

public void setPic(byte[] pic) {
    this.pic = pic;
}

@Action(value="sports")
@Override
public String execute() throws Exception {
    Session session= new     AnnotationConfiguration().configure().buildSessionFactory().openSession();

    Transaction t= session.beginTransaction();

    l=session.createCriteria(SportsSetterAndGetter.class).list();

    Iterator itr1=l.iterator();

    SportsSetterAndGetter s=new SportsSetterAndGetter();

    while (itr1.hasNext()) {
        s=(SportsSetterAndGetter)itr1.next();

        System.out.println("values are"+s.getSid());
        System.out.println(s.getName());
        System.out.println(s.getRate());
        System.out.println(s.getStatus());
        System.out.println(s.getStype());

        pic=s.getImage();           

    }



    return "success";
}
}

在Jsp页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:iterator value="l">
<s:property value="sid" />
<h1><s:property value="name" /></h1>
<h3><s:property value="rate" /></h3>
<h3><s:property value="status" /></h3>
<s:property value="stype" />
<img src="<s:property value="image" />" />
</s:iterator>
</body>
</html>

我从数据库中获取此值但我无法获取图像。我应该写什么来获取图像。

1 个答案:

答案 0 :(得分:3)

        BASE64Encoder base64Encoder = new BASE64Encoder();
        StringBuilder imageString = new StringBuilder();
        imageString.append("data:image/png;base64,");
        imageString.append(base64Encoder.encode(bytes));
        String image = imageString.toString();

您可以将此图像字符串设置为您的模型并将其发送到您的jsp并设置为您的src,如

<img src="<s:property value="image" />" />