gpt4 book ai didi

Spring MVC 预填充复选框

转载 作者:行者123 更新时间:2023-12-04 18:32:14 25 4
gpt4 key购买 nike

第一个小背景信息。获得了一个相当标准的用户角色关系,其中用户可以拥有许多角色。我将角色定义为用户类中的一个集合。现在我知道 html 表单将所有值作为字符串,并尝试获取值,因为我的自定义角色对象不起作用。我实现了一个 initbinder 将 id 转换回对象,以便我可以从我的复选框中检索选定的值,这部分工作。

但我似乎无法回头。我从已经具有角色的数据库中检索了一个用户,并希望使用用户拥有的所有角色预先填充角色复选框。基于这个例子:

Checkboxes example

他们说:

form:checkboxes items="${dynamic-list}" path="property-to-store"

For multiple checkboxes, as long as the “path” or “property” value is equal to any of the “checkbox values – ${dynamic-list}“, the matched checkbox will be checked automatically.



我对此的解释是,我应该能够为其提供一组所有角色,并将路径定义为来自 User 对象的角色,并且它应该与它们匹配,从而导致复选框预先填充。

那里的每个示例似乎都将动态​​列表的值作为字符串 []。好吧,这很棒而且很花哨,但是这对于我们定义为 Set 的自定义对象如何工作?我仍然可以将这一行定义用于复选框,还是我还需要在 View 中进行某种数据绑定(bind)标题?

这是我的用户 dto、用户 Controller 、自定义表单活页夹和用户编辑页面。

用户 DTO
@Entity
@Table
public class User extends BaseDto
{
@Column(updatable = false) @NotBlank
private String username;

@Column(name = "encrypted_password") @Size(min = 6, message = "password must be at least 6 characters") @Pattern(regexp = "^\\S*$", message = "invalid character detected")
private String password;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column @NotNull
private boolean enabled;

@Column @Email @NotBlank
private String email;

@Transient
private String confirmPassword;

@ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER, cascade = CascadeType.REFRESH) @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;

public User()
{
}

public User(final String usernameIn, final String passwordIn, final String firstNameIn, final String lastNameIn, final String emailIn, final boolean enabledIn)
{
username = usernameIn;
password = passwordIn;
firstName = firstNameIn;
lastName = lastNameIn;
email = emailIn;
enabled = enabledIn;
}

public String getUsername()
{
return username;
}

public void setUsername(final String usernameIn)
{
username = usernameIn;
}

public String getPassword()
{
return password;
}

public void setPassword(final String passwordIn)
{
password = passwordIn;
}

public String getFirstName()
{
return firstName;
}

public void setFirstName(final String firstNameIn)
{
firstName = firstNameIn;
}

public String getLastName()
{
return lastName;
}

public void setLastName(final String lastNameIn)
{
lastName = lastNameIn;
}

public String getEmail()
{
return email;
}

public void setEmail(final String emailIn)
{
email = emailIn;
}

public String getConfirmPassword()
{
return confirmPassword;
}

public void setConfirmPassword(final String confirmPasswordIn)
{
confirmPassword = confirmPasswordIn;
}

public boolean isEnabled()
{
return enabled;
}

public void setEnabled(final boolean enabledIn)
{
enabled = enabledIn;
}

public Set<Role> getRoles()
{
return roles;
}

public void setRoles(final Set<Role> rolesIn)
{
roles = rolesIn;
}
}

用户 Controller
@Controller @RequestMapping("/user")
public class UserController
{
@Autowired private UserService userService;
@Autowired private UserDao userDao;
@Autowired private RoleDao roleDao;

@InitBinder
public void bindForm(final WebDataBinder binder)
{
binder.registerCustomEditor(Set.class, "roles", new CustomFormBinder<RoleDao>(roleDao, Set.class));
}

@RequestMapping(method = RequestMethod.GET)
public String index(final ModelMap modelMap)
{
return "/user/index";
}

@RequestMapping(value = "/create", method = RequestMethod.GET)
public String create(final ModelMap modelMap)
{
modelMap.addAttribute("userInstance", new User());
modelMap.addAttribute("validRoles", new HashSet<Role>(roleDao.findAll()));

return "/user/create";
}

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(final ModelMap modelMap, @Valid @ModelAttribute("userInstance") final User user, final BindingResult bindingResult)
{
// TODO move to service validation
if (user.getPassword() == null || !user.getPassword().equals(user.getConfirmPassword()) )
{
bindingResult.addError(new FieldError("userInstance", "password", "password fields must match"));
bindingResult.addError(new FieldError("userInstance", "confirmPassword", "password fields must match"));
}
if (user.getRoles() == null || user.getRoles().isEmpty())
{
bindingResult.addError(new FieldError("userInstance", "roles", "Must select at least one role for a User"));
}
if (bindingResult.hasErrors())
{
modelMap.addAttribute("validRoles", new HashSet<Role>(roleDao.findAll()));
return "/user/create";
}

userService.save(user);
return "redirect:/user/list";
}

@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public String edit(@PathVariable final Integer id, final ModelMap modelMap)
{
final User user = userDao.find(id);

if (user != null)
{
modelMap.addAttribute("userInstance", user);
modelMap.addAttribute("validRoles", new HashSet<Role>(roleDao.findAll()));
return "/user/edit";
}
return "redirect:/user/list";
}

@RequestMapping(value = "/edit", method = RequestMethod.GET)
public String editCurrent(final ModelMap modelMap)
{
return edit(userService.getLoggedInUser().getId(), modelMap);
}

@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(@Valid @ModelAttribute("userInstance") final User user, final BindingResult bindingResult)
{
if (bindingResult.hasErrors())
{
return "/user/edit";
}

userService.save(user);
return "redirect:/user/list";
}

@ModelAttribute("userInstances")
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<User> list()
{
return userDao.findAll();
}
}

自定义表单活页夹
public class CustomFormBinder<T extends GenericDao> extends CustomCollectionEditor
{
private final T dao;

private static final Logger LOG = LoggerFactory.getLogger(CustomFormBinder.class);

public CustomFormBinder(final T daoIn, final Class collectionType)
{
super(collectionType, true);
dao = daoIn;
}

@Override
protected Object convertElement(final Object element)
{
try
{
// forms should return the id as the itemValue
return dao.find(Integer.valueOf(element.toString()));
}
catch (NumberFormatException e)
{
LOG.warn("Unable to convert " + element + " to an integer");
return null;
}
}

}

用户编辑 View
    <html>
<head>
<title>Create User</title>
</head>
<body>

<c:url value="/user/update" var="actionUrl"/>
<form:form method="post" commandName="userInstance" action="${actionUrl}">
<h1>Edit User ${userInstance.username}</h1>

<div>
<form:label path="username">Username:</form:label>
<form:input path="username" id="username" readonly="true"/>
</div>

<div>
<form:label path="password">Password:</form:label>
<form:input path="password" id="password" type="password" readonly="true"/>
<tag:errorlist path="userInstance.password" cssClass="formError"/>
</div>

<div>
<form:label path="firstName">First Name:</form:label>
<form:input path="firstName" id="firstName"/>
<tag:errorlist path="userInstance.firstName" cssClass="formError"/>
</div>

<div>
<form:label path="lastName">Last Name:</form:label>
<form:input path="lastName" id="lastName"/>
<tag:errorlist path="userInstance.lastName" cssClass="formError"/>
</div>

<div>
<form:label path="email">Email:</form:label>
<form:input path="email" id="email" size="30"/>
<tag:errorlist path="userInstance.email" cssClass="formError"/>
</div>

<div>
**<%--Want to Pre Populate these checkboxed--%>
<form:checkboxes title="Assigned Roles:" path="roles" id="roles" items="${validRoles}" itemLabel="displayName" itemValue="id" element="div"/>**
<tag:errorlist path="userInstance.roles" cssClass="formError"/>
</div>

<form:hidden path="enabled"/>
<form:hidden path="id"/>
<form:hidden path="version"/>

<div class="submit">
<input type="submit" value="Update"/>
<a href="<c:url value='/user/list'/>" class="cancel">Cancel</a>
</div>
</form:form>

</body>
</html>

最佳答案

您需要为 Role 正确实现 equals 方法!

如果这还不够,请查看类(class) oorg.springframework.web.servlet.tags.form.AbstractCheckedElementTag .方法void renderFromValue(Object item, Object value, TagWriter tagWriter)是设置检查标志的位置。

关于Spring MVC 预填充复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6989711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com