【问题标题】:Servlet, Jsp and Hibernate. How to print a query result in a jsp pageServlet、Jsp 和休眠。如何在jsp页面中打印查询结果
【发布时间】:2018-04-26 10:24:43
【问题描述】:

我有一个 Java Servlet,它使用休眠从数据库中获取消息列表。

protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
    SessionFactory factory = session.getSessionFactory();
    Session s = factory.openSession(); 
    List<Message> messages = s.createQuery("FROM Message").list();
    //print this list in home.jsp
}

如何将此消息发送到 home.jsp?

【问题讨论】:

标签: java hibernate jsp servlets


【解决方案1】:

伺服器:

 protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        SessionFactory factory = session.getSessionFactory();
        Session s = factory.openSession(); 
        List<Message> messages = s.createQuery("FROM Message").list();

        //associate with a request attribute
        request.setAttribute("messages", message);

        //forward to your JSP
        request.getRequestDispatcher("messages.jsp").forward(request, response);
    }

JSP

<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>

<html>
   <body>
      <%-- will iterate the messages collection put in 
           request scope in the servlet --%>
      <c:forEach items="${messages}" var="message">
         Message = ${message.someProperty"}
      </c:forEach>
   </body>
</html>

有用的参考资料:

https://www.tutorialspoint.com/jsp/jstl_core_foreach_tag.htm https://www.tutorialspoint.com/jsp/jsp_expression_language.htm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    相关资源
    最近更新 更多