如何将信息从 servlet 传递到 JSP 页面 [英] How do I pass information from a servlet to a JSP page

查看:35
本文介绍了如何将信息从 servlet 传递到 JSP 页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能有一个 servlet 包含一个对象(在本例中为 ArrayList),然后执行与显示 jsp 页面并将该对象传递给 jsp 页面的等效操作.在这种情况下,ArrayList 包含数据库结果,我想遍历并在 JSP 页面上显示结果.

我没有使用任何 MVC 框架,是否可以使用基本的 Servlet/JSP 架构来做到这一点.

解决方案

是.

  1. 在servlet调用request.setAttribute("result", yourArrayList);
  2. 然后转发到jsp:

    getServletContext().getRequestDispatcher("your.jsp").forward(请求,响应);

  3. 使用JSTL,在jsp中:

    ...</c:forEach>

如果您不想使用 JSTL(但我建议使用它),那么您也可以在 JSP 中使用 request.getAttribute("result") 获取值.>

另外,但不推荐,如果您想使用 redirect() 而不是 ,您可以使用 request.getSession().setAttribute(..) 代替>forward().

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.

I am not using any MVC framework, is it possible to do this with the basic Servlet/JSP architecture.

解决方案

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().

这篇关于如何将信息从 servlet 传递到 JSP 页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆