如何使用 jstl、servlet 在 jsp 中显示输出

how output display in jsp using jstl, servlet

对不起我的英语。我开始研究javaEE的技术,有些点我不太清楚。我使用 Maven 和模式 DAO。在数据库中我添加了图像,但我不知道它的图像如何使用 jstl 和 servlet 从 jsp 输出。请告诉我如何获取jsp

中的图片

对象classPost:

public class Posts {

//code

    @Lob
    @Column(name="IMAGE", nullable=false)
    private byte[] image;
}

//code

public void setImage(byte[] image) { this.image = image; }
public byte[] getImge() { return image; }
}

PostDao接口:

public interface PostDao {
//code
public Collection getAllPost();
}

PostDaoImpl

public class PostDaoImpl implements PostDao{
//code
    public Collection getAllPost() { //this method return list object
        Session session = null;
        List posts = new ArrayList<Posts>();
        try{
            session = HibernateUtil.getSessionFactory().openSession();
            posts = session.createCriteria(Posts.class).list();

        } catch(Exception e) { outputError("getAllPost", e); 
        } finally { closeSession(session); }
        return posts;
    }
//code
}

在 servlet 中 indexuser

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        //get session
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        try{
            //get collection allpost object
            Collection allpost = Factory.getInstance().getPostDAO().getAllPost();

            request.setAttribute("allpost", allpost);

            request.getRequestDispatcher("/index.jsp").forward(request, response); 
        } catch(Exception e) { 
            System.out.println(e);
        } finally{
            if(session!=null && session.isOpen())
                session.close();
        }
    }

index.jsp使用JSTL

<c:forEach var="allpost" items="${allpost}">
        <img src="${allpost.image}" alt="...">
</c:forEach>

错误:

javax.el.PropertyNotFoundException: Property 'image' not readable on type app.web.landingpage.object.Posts at javax.el.BeanELResolver$BeanProperty.read(BeanELResolver.java:297) at javax.el.BeanELResolver$BeanProperty.access[=16=]0(BeanELResolver.java:245) at javax.el.BeanELResolver.getValue(BeanELResolver.java:85) .............

您的 Posts#getImge 有错字,应该是 Posts#getImage。当您使用 EL 访问 class 的 属性 时,它将调用 属性 的 get 方法。

因此请按如下方式更改您的Post

public class Posts {
    @Lob
    @Column(name="IMAGE", nullable=false)
    private byte[] image;

    //code

    public void setImage(byte[] image) { this.image = image; }
    public byte[] getImage() { return image; }
}