我将为此创建一个EL函数。
package com.example;import java.util.Collection;public final class Functions { private Functions() { // } public static boolean contains(Collection<Object> collection, Object item) { return collection.contains(item); }}/WEB-INF/functions.tld像这样定义
<?xml version="1.0" encoding="UTF-8" ?><taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" version="2.1"> <display-name>Custom Functions</display-name> <tlib-version>1.0</tlib-version> <uri>http://example.com/functions</uri> <function> <name>contains</name> <function-class>com.example.Functions</function-class> <function-signature>boolean contains(java.util.Collection, java.lang.Object)</function-signature> </function></taglib>
然后您可以按以下方式使用它
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><%@taglib uri="http://example.com/functions" prefix="f" %>...<select name="roles" multiple> <c:forEach items="${allRoles}" var="role"> <option value="${role.id}" ${f:contains(user.roles, role) ? 'selected' : ''}>${role.name}</option> </c:forEach></select>更新
:为了集合中恰当地比较对象,必须实施
equals()和
hashCode()相应。您似乎还没有这样做。这是一个按技术ID进行比较的基本示例:
public boolean equals(Object other) { return other instanceof Role && id != null ? id.equals(((Role) other).id) : other == this;}public int hashCode() { return id != null ? getClass().hashCode() + id.hashCode() : super.hashCode();}


