簡體   English   中英

將Bean從Servlet加載到JSP

[英]Load Bean from Servlet to JSP

我已經搜索了很多,但是找不到我的錯誤。 我有一個servlet並嘗試將ArrayList放入bean中:

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

在“ showClients.jsp”中,我嘗試打印客戶端的電話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() ); %>

但是我有一個NullPointerException,因為我的對象列表為null。 我怎樣才能訪問Bean內ArrayList內的object(Client)內的變量(getPhone())?

經過更多測試后,我嘗試不使用Bean直接訪問我的ArrayList並工作,打印客戶端電話!

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

但是我需要使用一個bean,我只是做一個測試,所以有人可以幫助我嗎?

為什么不使用EL(表達語言)? 要訪問第二個項目,該句子將為${listClients.list[1].phone}

如果不能使用EL,則在使用useBean標記時已經聲明了一個變量,因此可以直接訪問Bean。

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

我建議您檢查getList方法是否正確返回列表。

我希望這能幫到您

檢查是否正在加載正確的.jars。 通常,對於這種東西,您需要一些特定的jar才能在服務器上運行JSP / servlet。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM