作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Spring MVC,我希望它从数据库中绑定(bind)一个持久对象,但我无法弄清楚如何设置我的代码以在绑定(bind)之前调用数据库。例如,我正在尝试将“BenefitType”对象更新到数据库,但是,我希望它从数据库中获取对象,而不是创建新对象,因此我不必更新所有字段。
@RequestMapping("/save")
public String save(@ModelAttribute("item") BenefitType benefitType, BindingResult result)
{
...check for errors
...save, etc.
}
最佳答案
有几种选择:
hidden
如有必要),并在提交后获得完全绑定(bind)的对象。复杂的属性也可以使用 PropertyEditor
绑定(bind)到表单域。 s。 GET
之间存储你的对象。和 POST
要求。 Spring 3 通过 @SessionAttributes
促进了这种方法。注释(来自 Petclinic sample ):@Controller
@RequestMapping("/owners/*/pets/{petId}/edit")
@SessionAttributes("pet") // Specify attributes to be stored in the session
public class EditPetForm {
...
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
// Disallow binding of sensitive fields - user can't override
// values from the session
dataBinder.setDisallowedFields("id");
}
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@PathVariable("petId") int petId, Model model) {
Pet pet = this.clinic.loadPet(petId);
model.addAttribute("pet", pet); // Put attribute into session
return "pets/form";
}
@RequestMapping(method = { RequestMethod.PUT, RequestMethod.POST })
public String processSubmit(@ModelAttribute("pet") Pet pet,
BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "pets/form";
} else {
this.clinic.storePet(pet);
// Clean the session attribute after successful submit
status.setComplete();
return "redirect:/owners/" + pet.getOwner().getId();
}
}
}
关于Spring MVC 3.0 : How do I bind to a persistent object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3672100/
我是一名优秀的程序员,十分优秀!