简体   繁体   中英

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.

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM