Home > Net >  How can I sort an array with JSTL?
How can I sort an array with JSTL?

Time:08-09

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.

CodePudding user response:

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>

CodePudding user response:

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" %>

  • Related