如何在具有选定值的jsp / jstl中进行多选?
您好我有一个用户有一些角色User.class
public class User { private Long id; private String firstName; private String lastName; private Set roles = new HashSet(0);
public Long getId(){return id; public void setId(Long id){this.id = id; }
public String getFirstName() { return this.firstName; } public void setFirstName(String firstname) { this.firstName = firstname; } public String getLastName() { return this.lastName; } public void setLastName(String lastname) { this.lastName = lastname; } public Set getRoles() { return this.roles; } public void setRoles(Set roles) { this.roles = roles; } }
Role.class
public class Role { private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
在jsp文件中,我想进行一个多选,它将具有所选值的所有角色(用户拥有的角色)。
我试过了:
<option value="${role.id}" selected >${role.name}
其中allRoles表示所有角色,roleSelected表示user.roles。 但它不起作用,有没有任何方式在jstl中说“如果在user.roles中的角色然后选择”? 感谢任何建议。
更新 :
不知怎的,它不工作,我把一个记录器放在那个类我有这个:
public static boolean contains(Collection collection, Object object) { System.out.println("coll = " + collection.toString()); System.out.println("obj="+ object.toString()); System.out.println("res="+ collection.contains(object)); return collection.contains(object); }
在日志中我有这个,它应该在第二次测试中得到结果:
coll = [Id :2;Code: TESTName: Temp Manager;Enabled: true;Comment: ;] obj=Id :1;Code: ADMName: ADMIN;Enabled: true;Comment: For Adminstrators; res=false coll = [Id :2;Code: TESTName: Temp Manager;Enabled: true;Comment: ;] obj=Id :2;Code: TESTName: Temp Manager;Enabled: true;Comment: ; res=false coll = [Id :2;Code: TESTName: Temp Manager;Enabled: true;Comment: ;] obj=Id :3;Code: RHHName: TECHNOMEDIA;Enabled: true;Comment: Dfdf; res=false coll = [Id :2;Code: TESTName: Temp Manager;Enabled: true;Comment: ;] obj=Id :4;Code: RESPONSName: Refd;Enabled: true;Comment: Sdsds; res=false
我会为此创建一个EL函数。
package com.example; import java.util.Collection; public final class Functions { private Functions() { // } public static boolean contains(Collection
在/WEB-INF/functions.tld
定义它
Custom Functions 1.0 http://example.com/functions contains com.example.Functions boolean contains(java.util.Collection, java.lang.Object)
然后你可以按如下方式使用它
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@taglib uri="http://example.com/functions" prefix="f" %> ...
更新 :为了正确比较集合中的对象,您必须相应地实现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(); }
也可以看看:
- HashSet无法识别相同的对象
- 理解equals和hashcode
- 覆盖equals和hashcode
- 实现equals和hashcode的正确方法