Saphire
Saphire

Reputation: 1930

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?

Upvotes: 0

Views: 40

Answers (3)

user2575725
user2575725

Reputation:

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

Upvotes: 2

Arshad Ali
Arshad Ali

Reputation: 3274

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>

Upvotes: 1

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40318

Since your <jsp:useBean> defines scope="session", your servlet should do (before calling the RequestDispatcher):

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

Upvotes: 0

Related Questions