How do I pass information from a servlet to a JSP page

后端 未结 4 1189
日久生厌
日久生厌 2020-12-06 02:45

Is it possible to have a servlet that contains an object (an ArrayList in this case) that then does the equivalent of displaying a jsp page and passing that object to the js

相关标签:
4条回答
  • 2020-12-06 03:10

    Yes.

    1. in the servlet call request.setAttribute("result", yourArrayList);
    2. then forward to the jsp:

      getServletContext().getRequestDispatcher("your.jsp")
          .forward(request, response);
      
    3. using JSTL, in the jsp:

      <c:forEach items="${result}" var="item">
        ...
      </c:forEach>
      

    If you don't want to use JSTL (but I recommend using it), then you can get the value using request.getAttribute("result") in the JSP as well.

    Alternatively, but not recommended, you can use request.getSession().setAttribute(..) instead, if you want to redirect() rather than forward().

    0 讨论(0)
  • 2020-12-06 03:12

    If you are trying to make some kind of "component" then it's better to convert the JSP page into a custom tag. Here is excellent article about that: http://onjava.com/pub/a/onjava/2004/05/12/jsp2part4.html

    0 讨论(0)
  • 2020-12-06 03:23

    You can put it using request.setAttribute("myobj", myObj); see javadoc

    0 讨论(0)
  • 2020-12-06 03:29

    You can pass objects to jsp's by embedding them within the Request.

    request.setAttribute("object", object);

    and within the jsp:

    request.getAttribute("object");

    0 讨论(0)
提交回复
热议问题