Use request.getAttribute ("key"))

0

I'm passing a List list and want to retrieve it in jsp through the request.getAttribute ("key"):

@Override
protected doGet(HTTPServlet request, HTTPServletResponse response)
   throw new ServletException {

  List<Hotel> hotel=Hotel.listar();
  request.setAttribute("key", hoteis);

  RequestDispatcher rd=request.getRequestDispatcher("./hotel/exibe_hoteis.jsp");
  rd.forward(request, response);
}

In jsp I do:

    
asked by anonymous 01.12.2016 / 19:48

1 answer

1

Good afternoon André Nascimento,

To recover the list in the request.getAttribute(); attribute, there are two ways.

  • Using scriptlets
  • Using the JSTL framework

Using Scriptlets

Your code will look something like this:

<% List hoteis = (List) request.getAttribute("key"); %>

At this point you will already have access to the hotels through the variable hoteis . Dai just iterate all the hotels inside a for and display them for the user.

<table>
   <thead>
      <th>Nome do hotel</th>
      <th>Preço da estadia</th>
   </thead>
   <tbody>
      <% for(int i = 0; i < hoteis.size(); i++) {%>
       <tr>
        <td><%= hoteis.get(i).getNomeHotel() %></td>
        <td><%= hoteis.get(i).getPrecoEstadia() %></td>
       </tr>
       <%}%>
   </tbody>
</table>

I'm assuming that your hotel class has the attributes:   hotel name and precoEstadia , so include in the code, but you can use your own attributes.

Using the JSTL framework

To run a for loop within JSTL you use the <c:forEach></c:forEach>

Your code will look something like this:

<table>
   <thead>
      <th>Nome do hotel</th>
      <th>Preço da estadia</th>
   </thead>
   <tbody>
      <c:forEach items="${requestScope.hoteis}" var="hotel">
       <tr>
        <td>
          ${hotel.nomeHotel}
        </td>
        <td>
         ${hotel.precoEstadia}
        </td>
       </tr>
      </c:forEach>
   </tbody>
</table>

Done, this way you will be able to view all items normally.

I hope I have helped.

    
02.12.2016 / 18:24