Login Or Sign up

How can I sort an array with JSTL?

375 Views Asked by At

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.

2

There are 2 best solutions below

0
Cheng Thao On BEST ANSWER

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>
0
hyunjung_jay On

Did you put the taglib on the top of jsp?

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

Actually it's fine to put one (1)

but usually we put the other together

like this

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

<%@ taglib prefix="fn" uri = "http://java.sun.com/jsp/jstl/functions" %>

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>