[英]How do I pass information from a servlet to a JSP page
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. 是否可以拥有一个包含一个对象(在本例中为一个ArrayList)的servlet,该servlet相当于显示一个jsp页面并将该对象传递给jsp页面。 In this case the ArrayList contains database results an I want to iterate through and display the results on the JSP page.
在这种情况下,ArrayList包含我想要迭代的数据库结果并在JSP页面上显示结果。
I am not using any MVC framework, is it possible to do this with the basic Servlet/JSP architecture. 我没有使用任何MVC框架,是否可以使用基本的Servlet / JSP架构来实现。
Yes. 是。
request.setAttribute("result", yourArrayList);
request.setAttribute("result", yourArrayList);
then forward to the jsp: 然后转发到jsp:
getServletContext().getRequestDispatcher("your.jsp") .forward(request, response);
using JSTL, in the jsp: 在jsp中使用JSTL:
<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. 如果您不想使用JSTL(但我建议使用它),那么您也可以使用JSP中的
request.getAttribute("result")
来获取值。
Alternatively, but not recommended, you can use request.getSession().setAttribute(..)
instead, if you want to redirect()
rather than forward()
. 或者,但不推荐,您可以使用
request.getSession().setAttribute(..)
,如果您想redirect()
而不是forward()
。
You can pass objects to jsp's by embedding them within the Request. 您可以通过将对象嵌入到请求中来将对象传递给jsp。
request.setAttribute("object", object);
and within the jsp: 并在jsp内:
request.getAttribute("object");
If you are trying to make some kind of "component" then it's better to convert the JSP page into a custom tag. 如果您正在尝试制作某种“组件”,那么最好将JSP页面转换为自定义标记。 Here is excellent article about that: http://onjava.com/pub/a/onjava/2004/05/12/jsp2part4.html
以下是关于此的优秀文章: http : //onjava.com/pub/a/onjava/2004/05/12/jsp2part4.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.