弹簧形式:选择多个选定值? [英] Spring form:select multiple selected value?
问题描述
我有此编辑表单:
我希望选择用户的角色.如果这是一对多关系,我知道我可以做这样的事情:
I want that the roles of the user get selected. If this were one-to-many relation I know that I can do something like this:
<form:label path="roles">Roles:</form:label>
<form:select multiple="true" path="roles">
<c:forEach items="${roles}" var="rol">
<c:choose>
<c:when
test="${usuarioEdit.rol.id ==rol.id}">
<option value="${rol.id}" selected="selected">${rol.nombre}</option>
</c:when>
<c:otherwise>
<option value="${rol.id}">${rol.nombre}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</form:select>
<form:errors cssStyle="color:red" path="roles"></form:errors>
但这是一个多对多的关系.如何在编辑表单中选择选项?有简单的表格吗?
But this is a many-to-many relation. How can I get selected the options in an edit form?. Is there an easy form?
此代码有效,但我想知道spring是否提供了任何便利:
This code works, but I wonder if spring gives any facilities:
<form:select multiple="true" path="roles">
<c:forEach items="${roles}" var="rol">
<c:set var="isSelected" value="false" />
<c:forEach items="${rolesUsu}" var="rolUsu">
<c:if test="${rolUsu.getRol().getId()==rol.id}">
<c:set var="isSelected" value="true" />
</c:if>
</c:forEach>
<c:choose>
<c:when test="${isSelected}">
<option value="${rol.id}" selected="selected">${rol.nombre}</option>
</c:when>
<c:otherwise>
<option value="${rol.id}">${rol.nombre}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</form:select>
在我的控制器中,我有:
In my controller I have:
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Set.class, "roles",
new RolCollectionEditor(Set.class, rolDao));
}
RolCollectionEditor:
RolCollectionEditor:
public class RolCollectionEditor extends CustomCollectionEditor {
private final RolDAO rolDao;
public RolCollectionEditor(Class<?> collectionType, RolDAO rolDao) {
super(collectionType);
this.rolDao = rolDao;
}
@Override
protected Object convertElement(Object element) {
String rolId = (String) element;
Rol rol = rolDao.findById(rolId);
Usuario_Rol usuRol = new Usuario_Rol();
//Agregamos un usuario vacio temporal
//y lo sobreescribimos en el controlador
Usuario usuario = new Usuario();
usuRol.setUsuario(usuario);
usuRol.setRol(rol);
usuRol.setFechaCreacion(new Date());
usuRol.setFechaModificacion(new Date());
usuRol.setStatus("activo");
return usuRol;
}
}
此处Usuario_Rol是多对多关系的中间表,除了userId和rolId外,它还具有其他属性.
Here Usuario_Rol is an intermediate table for the many to many relation, that have other attributes besides the userId and rolId.
角色类:
@Entity
@Table(name = "rol", uniqueConstraints = { @UniqueConstraint(columnNames = "nombre") })
public class Rol implements Serializable{
@Id
@Column(name = "_id")
private String id;
@Column(name = "nombre")
@NotNull
private String nombre;
@Column(name = "descripcion")
private String descripcion;
@Column(name = "status")
private String status;
@Column(name = "fechaCreacion")
private Date fechaCreacion;
@Column(name = "fechaModificacion")
private Date fechaModificacion;
@Column(name = "fechaSincronizacion")
private Date fechaSincronizacion;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "usuarioRol_pk.rol", orphanRemoval = true, cascade=CascadeType.ALL)
private Set<Usuario_Rol> usuarios = new HashSet<Usuario_Rol>(0);
//getters and setters
@Override
final public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((nombre == null) ? 0 : nombre.hashCode());
return result;
}
@Override
final public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Rol))
return false;
Rol other = (Rol) obj;
if (nombre == null) {
if (other.nombre != null)
return false;
} else if (!nombre.equals(other.nombre))
return false;
return true;
}
Usuario类:
@实体 @Table(name ="usuario",uniqueConstraints = { @UniqueConstraint(columnNames ="login"), @UniqueConstraint(columnNames ="correo")}) 公共类Usuario实现了Serializable {
@Entity @Table(name = "usuario", uniqueConstraints = { @UniqueConstraint(columnNames = "login"), @UniqueConstraint(columnNames = "correo") }) public class Usuario implements Serializable {
@Id
@Column(name = "_id")
private String id;
@Column(name = "nombre")
@NotEmpty
private String nombre;
@Column(name = "apellido")
@NotEmpty
private String apellido;
@Column(name = "login")
@Size(min = 4)
@NotEmpty
private String login;
@Column(name = "password")
@NotEmpty
@Size(min = 4)
private String password;
@Column(name = "salt")
private String salt;
@Column(name = "correo")
@NotEmpty
@Email
private String correo;
@Column(name = "token")
private String token;
@Column(name = "status")
private String status;
@Column(name = "fechaUltimoLogin")
private Date fechaUltimoLogin;
@Column(name = "fechaCreacion")
private Date fechaCreacion;
@Column(name = "fechaModificacion")
private Date fechaModificacion;
@Column(name = "fechaSincronizacion")
private Date fechaSincronizacion;
@NotEmpty
@OneToMany(fetch = FetchType.EAGER, mappedBy = "usuarioRol_pk.usuario", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<Usuario_Rol> roles = new HashSet<Usuario_Rol>(0);
//constructor, getters and setters.
@Override
final public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((login == null) ? 0 : login.hashCode());
return result;
}
@Override
final public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Usuario))
return false;
Usuario other = (Usuario) obj;
if (login == null) {
if (other.login != null)
return false;
} else if (!login.equals(other.login))
return false;
return true;
}
中级班:
@Entity
@Table(name = "usuario_rol")
@AssociationOverrides({
@AssociationOverride(name = "usuarioRol_pk.usuario", joinColumns = @JoinColumn(name = "idUsuario")),
@AssociationOverride(name = "usuarioRol_pk.rol", joinColumns = @JoinColumn(name = "idRol"))
})
public class Usuario_Rol implements Serializable{
@EmbeddedId
private Usuario_RolId usuarioRol_pk = new Usuario_RolId();
@Temporal(TemporalType.DATE)
@Column(name = "fechaCreacion")
private Date fechaCreacion;
@Temporal(TemporalType.DATE)
@Column(name = "fechaModificacion")
private Date fechaModificacion;
@Temporal(TemporalType.DATE)
@Column(name = "fechaSincronizacion")
private Date fechaSincronizacion;
@Column(name = "status")
private String status;
//gettters, setters
@Override
final public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((usuarioRol_pk == null) ? 0 : usuarioRol_pk.hashCode());
return result;
}
@Override
final public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Usuario_Rol))
return false;
Usuario_Rol other = (Usuario_Rol) obj;
if (usuarioRol_pk == null) {
if (other.usuarioRol_pk != null)
return false;
} else if (!usuarioRol_pk.equals(other.usuarioRol_pk))
return false;
return true;
}
Usuario_RolId:
Usuario_RolId:
@Embeddable
public class Usuario_RolId implements Serializable{
@ManyToOne
private Usuario usuario;
@ManyToOne
private Rol rol;
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public Rol getRol() {
return rol;
}
public void setRol(Rol rol) {
this.rol = rol;
}
@Override
final public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((rol == null) ? 0 : rol.hashCode());
result = prime * result + ((usuario == null) ? 0 : usuario.hashCode());
return result;
}
@Override
final public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Usuario_RolId))
return false;
Usuario_RolId other = (Usuario_RolId) obj;
if (rol == null) {
if (other.rol != null)
return false;
} else if (!rol.equals(other.rol))
return false;
if (usuario == null) {
if (other.usuario != null)
return false;
} else if (!usuario.equals(other.usuario))
return false;
return true;
}
最后一个类用于模拟多对多关系的技巧.我遵循了本教程: http://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/
This last class is used for the trick of simulating a many to many relation. I have followed this tutorial: http://www.mkyong.com/hibernate/hibernate-many-to-many-example-join-table-extra-column-annotation/
推荐答案
为什么要编写自己的书? Spring应该能够为您做到这一点.用<form options .. />
标记代替整个块.然后,Spring就能自己进行选择(您可能需要 PropertyEditor .
Why are you writing your own? Spring should be able to do that for you. Instead of a <c:forEach />
replace that whole block with a <form options .. />
tags. Spring will then be able to do the selection itself (you might need a Converter or PropertyEditor for that).
<form:select multiple="true" path="roles" items="${roles}" itemLabel="nombre" itemValue="id" />
类似的事情……
链接:
- Form Options documentation
- Form Select documentation
- Reference Guide
这篇关于弹簧形式:选择多个选定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!