-2

I've a Java Servlet which takes a list of messages from a database using 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
}

How can I send this messages to home.jsp?

AkkyR
  • 19
  • 8
  • Possible duplicate of [How should I start Java-based web development?](https://stackoverflow.com/questions/1084591/how-should-i-start-java-based-web-development) – mohammedkhan Apr 26 '18 at 10:27

1 Answers1

1

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>

Useful references:

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

Alan Hay
  • 22,665
  • 4
  • 56
  • 110