Use request.getattribute("key"))

Asked

Viewed 148 times

0

I am passing a List list and want to recover in jsp through 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:

1 answer

1


Good Afternoon André Nascimento,

To retrieve the list in the attribute request.getAttribute(); 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. Then simply iterate all hotels within a for and display them to 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 your hotel class has the attributes: nomeHotel and early stadia, so include in the code, but you can use your own attributes.

Using the JSTL framework

To spin a loop for within the JSTL you use the tag <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>

There, that way you can display all the items normally.

I hope I’ve helped.

  • I added the line: <% List hotels = (List) request.getattribute("key"); %> , how do I import the usel. List?

  • managed to put <%@pageimport="java.util.List" %> thanks, thanks. I will do with your alternatives to learn.

  • Okay, good that you did. .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.