如何将信息从servlet传递到JSP页面 [英] How do I pass information from a servlet to a JSP page
问题描述
是否可以拥有一个包含对象(在本例中为ArrayList)的servlet,该servlet相当于显示一个jsp页面并将该对象传递给jsp页面。在这种情况下,ArrayList包含我想迭代的数据库结果并在JSP页面上显示结果。
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 jsp page. In this case the ArrayList contains database results an I want to iterate through and display the results on the JSP page.
我没有使用任何MVC框架,是否可以使用基本的Servlet / JSP架构来做到这一点。
I am not using any MVC framework, is it possible to do this with the basic Servlet/JSP architecture.
推荐答案
是。
- 在servlet调用
request.setAttribute(result,yourArrayList);
-
然后转发到jsp:
- in the servlet call
request.setAttribute("result", yourArrayList);
then forward to the jsp:
getServletContext().getRequestDispatcher("your.jsp")
.forward(request, response);
使用JSTL,在jsp中:
using JSTL, in the jsp:
<c:forEach items="${result}" var="item">
...
</c:forEach>
如果您不想使用JSTL (但我建议使用它),然后你也可以在JSP中使用 request.getAttribute(result)
获取值。
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.
或者,但不推荐,你可以使用 request.getSession()。setAttribute(..)
代替,如果你想 redirect()
而不是 forward()
。
Alternatively, but not recommended, you can use request.getSession().setAttribute(..)
instead, if you want to redirect()
rather than forward()
.
这篇关于如何将信息从servlet传递到JSP页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!