代码之家  ›  专栏  ›  技术社区  ›  michael mattanza

Servlet、Jsp和Hibernate。如何在jsp页面中打印查询结果

  •  -2
  • michael mattanza  · 技术社区  · 6 年前

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

    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
    }
    

    如何将此消息发送到家中。jsp?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Alan Hay    6 年前

    SERVLET:

     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