【发布时间】:2012-05-22 15:36:02
【问题描述】:
在使用 hibernate 保存对象之前预填充对象的最佳做法是什么?
我做了什么:
我的控制器:
//The Form
@RequestMapping(value = "user/{id}/edit", method = RequestMethod.GET)
public String edit(@PathVariable("id") Long userId, ModelMap modelMap) {
modelMap.addAttribute("user", userService.find(userId));
return "user/userEdit";
}
//Updating database
@RequestMapping(value = "user/edit", method = RequestMethod.POST)
public String update(@ModelAttribute("user") @Valid User user, BindingResult result,
RedirectAttributes redirectAttrs) {
if (result.hasErrors()) {
return "user/userEdit";
}else{
userService.update(user);
redirectAttrs.addFlashAttribute("message", "Success");
return "redirect:user/userEdit";
}
}
如果我创建一个包含所有字段(用户名、密码和 ID)的表单,它会起作用,但是如果我希望用户只更新密码,我应该怎么做?
由于我在用户名处有一个@NotEmpty,我收到一个错误,即用户名为空,因为它不在表单中,但我不想输入用户名字段,只输入密码。
我的 html 表单:
<c:url var="url" value="/user/edit" />
<form:form method="post" action="${url}" modelAttribute="user" class="form-horizontal">
<form:hidden path="id"/>
<form:hidden path="version"/>
<fieldset>
<div class="control-group">
<form:label cssClass="control-label" path="password"><spring:message code="user.label.password"/>: </form:label>
<div class="controls">
<form:input cssClass="input-xlarge" path="password" />
</div>
<form:errors path="password"/>
</div>
<div class="control-group">
<form:label cssClass="control-label" path="userRole"><spring:message code="user.label.role"/>: </form:label>
<div class="controls">
<form:select path="userRole">
<form:options items="${userRoleList}" itemValue="id" itemLabel="name"/>
</form:select>
</div>
<form:errors path="userRole"/>
</div>
<div class="control-group">
<form:label cssClass="control-label" path="costumer.id"><spring:message code="user.label.costumer"/>: </form:label>
<div class="controls">
<form:select path="costumer.id">
<form:options items="${costumerList}" itemValue="id" itemLabel="name"/>
</form:select>
</div>
<form:errors path="costumer.id"/>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save changes</button>
<a class="btn cancel link" href="<c:url value="/user" />">Cancel</a>
</div>
</fieldset>
</form:form>
- 我尝试使用@Sessionattributes,但如果我尝试使用它就无法正常工作 使用浏览器选项卡编辑两个或更多用户。
- 我尝试使用属性编辑器,但无法使用 @ModelAtrribute 用户用户。
- 我尝试使用转换器,但没有成功。
唯一的方法是先让用户 user = userService.find(id) ,然后设置更新的值吗?比如:
@RequestMapping(value = "user/edit", method = RequestMethod.POST)
public String update(@RequestParam("password") String password, BindingResult result, RedirectAttributes redirectAttrs) {
User user = userService.find(id);
if (password == null{
return "user/userEdit";
}else{
user.setPassword("password");
userService.update(user);
redirectAttrs.addFlashAttribute("message", "Success");
return "redirect:user/userEdit";
}
}
这看错了,因为没有验证。
【问题讨论】:
标签: java spring hibernate spring-mvc