在JSP中显示多个图像的最佳方法

时间:2014-09-18 14:39:57

标签: java jsp spring-mvc

我有一个JSP,我想从数据库中显示车辆的图像。我的实体类看起来像这样:

public class Vehicle implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id_vehicle")
    private int idVehicle;

    private String model;

    private String manufacturer;

    private byte[] image;

    @Transient
    private String encodedImage;

    // Getters and setters
}

在JSP中显示所有图像的一种方法如下所示:

<c:forEach items="${vehicles}" var="v">
    <img src="data:image/jpg;base64, <c:out value='${v.encodedImage}'/>"
        width="214" height="138" />
</c:forEach>

这意味着,字节数组被编码为String,所有内容都传递给新的List

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ba.spiderweb.carshop.dao.VehicleDao;
import ba.spiderweb.carshop.entity.Vehicle;
import ba.spiderweb.carshop.util.PageConverter;

@Service
@Transactional
public class VehicleServiceImpl implements VehicleService {

    @Autowired
    private VehicleDao vehicleDao;

    @Override
    public List<Vehicle> findAll() {
        List<Vehicle> finalList = new ArrayList<Vehicle>();
        for (Vehicle v : vehicleDao.findAll()) {
            v.setEncodedImage(new String(Base64.encodeBase64(v.getImage())));
            finalList.add(v);
        }
        return finalList;
    }
}

有没有更好的方法在JSP中显示多个图像,而不是先前将字节数组编码到String并重新创建新的List车辆?可能直接在JSP中编码字节数组吗?

1 个答案:

答案 0 :(得分:2)

制作一个将网址映射到图片文件内容的servlet。

html / jsp

<c:forEach items="${vehicles}" var="v">
   <img src="images/${v.idVehicle}"
    width="214" height="138" />
</c:forEach>

将在网址images/112/images/333上调用图片...这些数字是车辆ID。

servlet将使用此信息在数据库中查找车辆并提供其图像:

public class VehicleServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    String path = req.getPathInfo();

    //gets what comes after "/" (I've not tested it)
    String strVehicleId = path.substring(path.indexOf('/'));

    int vehicleId = Integer.parseInt(strVehicleId);
    //finds the vehicle
    Vehicle v = vehicleDao.findByPrimaryKey(vehicleId);

    //sends the image
    resp.setContentType("image/jpg");
    BufferedOutputStream out = new BufferedOutputStream(resp.getOutputStream());
    out.write(v.getImage());
    out.close();

}

并且不要忘记{&3;} / images / &#34;&#34; / images / &#34; web.xml配置文件中的路径。