简体   繁体   中英

Trying to access bean created in servlet via JSP

I am trying to access a bean I create in a servlet from a JSP. In my servlet BlogController.java I instantiate the bean like this

    BlogList bloglist = new BlogList();
    if (bloglist.getSize()<1) {
        bloglist.addDummies();
        //Now the size of the bloglist is 10
    }

Then, still in this servlet I call the jsp like

RequestDispatcher rd = request.getRequestDispatcher("/Blog7.jsp");
rd.forward(request, response);

and inside the JSP I am trying to use the bean like

<jsp:useBean id="bloglist" type="ub7.BlogList" scope="session"/>

but the size of bloglist is 0 here, why?

You will have to add the bean into the session at the servlet itself:

in servlet

HttpSession session = request.getSession();
session.setAttribute("bloglist", bloglist);
RequestDispatcher rd = request.getRequestDispatcher("/Blog7.jsp");
rd.forward(request, response);

in jsp

Blog List count: ${sessionScope.bloglist.size()}

Try this in servlet:

RequestDispatcher rd = request.getRequestDispatcher("/Blog7.jsp");
request.setAttribute("bloglist", bloglist); // Will be available as ${bloglist} in JSP
rd.forward(request, response);

and in JSP :

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
....
<table>
<c:forEach items="${bloglist}" var="blog">
    <tr>
        <td>${blog.name}</td>            
    </tr>
</c:forEach>
</table>

由于您的<jsp:useBean>定义了scope="session" ,因此您的servlet应该这样做( 调用RequestDispatcher 之前 ):

request.getSession().setAttribute("bloglist", bloglist);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM