Send a Servlet object array to a jsp page

Asked

Viewed 529 times

0

I need some help I have a Servlet that returns 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 (text box)

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 recover 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 it is necessary to lower the jars jstl-api and jstl-impl.

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

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  • Solved your problem?

  • In case, I have to use a foreach to traverse my object ? That’s it ?

  • If you want to access all the array indexes dynamically, yes. You could use Scriptlets or, better yet, JSTL.

  • I edited the answer including examples of how to iterate arrays on the JSP page.

  • Solved your problem? Give us feedback!

  • Hi. Yes. Actually I was trying to do this with an object. I saved the result of select on an object so it wasn’t working. I had to convert my object to array type to do this. But it worked, thank you !

  • Good. If that answer was the solution mark it as the solution.To finish the post.

Show 2 more comments

Browser other questions tagged

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