Send a servlet object array to a jsp page

0

I need some help I have a servlet that is returning an array object p with a select query. I would like to know how to display this object in my jsp in HTML input fields

    
asked by anonymous 16.10.2018 / 03:12

1 answer

3

You store as an attribute in your request:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String[] array = {"gato", "rato", "pato"};
    req.setAttribute("array", array);

    // Redirecionamento feito pelo servidor
    req.getRequestDispatcher("/list.jsp").forward(req, resp);
}

Then you retrieve in your jsp using EL (Expression Language) :

<body>
    <input type="text" value="${array[0]}"/>
    <input type="text" value="${array[1]}"/>
</body>

Iterating the array with Scriptlets :

<body>
   <% 
       String[] array = (String[])request.getAttribute("array");

       for (String nome : array) { %>
           <input type="text" value="<%= nome %>"/>
           <br/>
   <%  } %>
</body>

Iterating the array using JSTL :

<body>
    <c:forEach var="nome" items="${array}">
        <input type="text" value="${nome}"/>
        <br/>
    </c:forEach>
<body>

With JSTL you need to download the jars jstl-api and jstl-impl .

And you also need to reference the JSTL URI at the top of the JSP page so that you can use the taglibs:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
16.10.2018 / 13:12