Search code examples
javajspjstljava-ee-6jsp-tags

How can I sort an array with JSTL?


For example if a have this:

<form method="post">
    <c:forEach var = "i" begin = "0" end = "5">
        <input type="text" name="textbox">
    </c:forEach>
    <button type="submit" name="buttonSave">Save</button>
</form>
<c:set var="data" value="${paramValues.textbox}"/>
<c:forEach var = "item"  items="${data}">
    ${item}
</c:forEach>

How can I sort my array?, using JSTL if it's possible.


Solution

  • I don't think there's JSTL support for sorting of array or of collection. You either create your own custom tag to sort or you can just write Java code to perform the sort before processing it. See example below:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
      <body>
        <form action="index.jsp" method="post">
          <input type="text" name="items"><br>
          <input type="text" name="items"><br>
          <input type="text" name="items"><br>
          <input type="text" name="items"><br>
          <input type="submit" name="submit" value="submit">
        </form>
        <% String[] input = request.getParameterValues("items");
           if (input != null) {
              java.util.Arrays.sort(input);
              request.setAttribute("items", input);
           }
        %>
        <c:forEach var="item" items="${items}">
          <div>${item}</div>
        </c:forEach>
      </body>