Struts2多选择框预选当前选项
我创建了一个表格 & struts2 中用于编辑用户记录的操作,一个用户可能有一个或多个角色,我有一个表单,其中使用多个选择框来选择给定用户的角色。选择框内容是从数据库中读取的,我希望选择框在加载表单时预先选择用户当前的选项,使用在线找到的示例,我有以下内容。
在我的操作类中
public List<Role> getRoles()
{
return roles;
}
public void setRoles( List<Role> roles )
{
this.roles = roles;
}
public List<Role> getAvailableRoles()
{
return availableRoles;
}
在我的 JSP 中,
<s:select list="availableRoles" listKey="id" listValue="name" name="roles" label="Roles" multiple="true" />
多重选择框创建得很好,但是一开始就没有选择任何项目,我有点困惑,因为我发现的每个示例都是这样做的。
我确实尝试将选择框更改为这样:
<s:select list="availableRoles" name="roles" label="Roles" multiple="true" />
这种方式确实成功地预先选择了选项,但是随后下拉列表中填充了从我的 Role 类上的 toString() 方法返回的任何内容,而不是 getId() 和 getName( )这就是我想要的方法。有什么想法我哪里出错了吗?
I have created a form & action in struts2 for editing a User record, a User may have one or more Roles and I have a form were a multiple select box is used to select the roles for a given user. The select box contents is read from the database and I want the select box to pre-select the users current options when loading the form, using examples found online I have the following.
In my action class
public List<Role> getRoles()
{
return roles;
}
public void setRoles( List<Role> roles )
{
this.roles = roles;
}
public List<Role> getAvailableRoles()
{
return availableRoles;
}
In my JSP
<s:select list="availableRoles" listKey="id" listValue="name" name="roles" label="Roles" multiple="true" />
The multiple select box is created fine however no items are selected to begin with and I am a bit confused as every example I have found does just this.
I did try changing the select box to just this:
<s:select list="availableRoles" name="roles" label="Roles" multiple="true" />
This way does successfully pre-select the options however then the drop down is populated with whatever is returned from the toString() method on my Role class not specifically the getId() and getName() methods which is what I want. Any ideas where I am going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您的问题可能是
getRoles()
和setRoles()
需要是List
而不是List;
。这是因为 HTMLselect
使用字符串作为其键。将类型更改为List
并使用用户当前选项的角色 Id 初始化 Roles 变量。这是因为您有listkey=id
。您还需要multiple=true
。I think your problem might be that
getRoles()
andsetRoles()
needs to be aList<String>
notList<Roles>
. This is because HTMLselect
use strings for it's keys. Change the type toList<String>
and initialise the roles variable with the Id's of the roles for the user's current options. This is because you havelistkey=id
. You will needmultiple=true
as well.读完 struts2 源代码后,我的答案似乎相当明显。我需要在我的 Role 类上实现 .equals() 方法才能正常工作。
After reading through the struts2 source code it seems my answer was fairly obvious. I need to implement the .equals() method on my Role class for this to work.