Alessandro Melo
Alessandro Melo

Reputation: 39

Load Bean from Servlet to JSP

I already searched a lot but can't find my error. I have a servlet and try to put an ArrayList in a bean:

ClientBean c = new ClientBean();
c.setList(ClientsHandler.getAllClients());
request.setAttribute("listClients", c);
RequestDispatcher dispatcher = request.getRequestDispatcher("showClients.jsp");
dispatcher.forward(request, response);

In the "showClients.jsp" i try to print the phone of the client 1:

<jsp:useBean id="listClients" class="beans.ClientBean" scope="request"/>
<% ArrayList<ClientsRowGateway> list = ((beans.ClientBean)request.getAttribute("listClients")).getList(); %>
<% out.println( ""+list.get(1).getPhone() ); %>

But i have a NullPointerException, because my object list is null. How can i have access to a variable(getPhone()) inside of an object(Client) inside of an ArrayList inside of a bean???

After more tests, i try to access my ArrayList directly without a bean and works, print the client phone!

<%
ArrayList<ClientsRowGateway> testList = ClientsHandler.getAllClients();
if( testList != null )
    out.println( testList.get(1).getPhone() );
%>

But i need to use a bean, i just do this for a test, so can someone help me?

Upvotes: 1

Views: 1071

Answers (2)

Daniel M
Daniel M

Reputation: 16

Check if you are loading the correct .jars. Usually for this kind of stuff you need some specific jars to run JSP's/servlets on the server.

Upvotes: 0

Cesar Loachamin
Cesar Loachamin

Reputation: 2738

Why don't you use the EL (Expression Language)?? to access the second item the sentence will be ${listClients.list[1].phone}.

If you can't use EL, when you use the useBean tag you are already declaring an variable so you can access directly to the bean so.

<jsp:useBean id="listClients" class="beans.ClientBean" scope="request"/>
<% ArrayList<ClientsRowGateway> list = listClients.getList(); %>
<% out.println( ""+list.get(1).getPhone() ); %>

I suggest you to check if the getList method return correctly the list.

I hope this will help you

Upvotes: 1

Related Questions