Spring表单处理,将实体映射到表单输入 [英] Spring form handling, mapping an entity to form inputs

查看:327
本文介绍了Spring表单处理,将实体映射到表单输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是查看petclinic示例应用程序,并尝试学习表单处理。

Just looking at the petclinic sample application, and trying to learn form handling.

表单似乎映射到实体1:1正确吗?是否有任何其他配置需要完成,或者只是知道所有表单输入都映射到实体,因为这是在GET请求中添加到模型的内容?

It seems the form maps to an entity 1:1 correct? Is there any other configuration that has to be done, or will spring just know that all the form inputs map to the entity because that is what was added to the model in the GET request?

@Controller
@RequestMapping("/owners/*/pets/{petId}/visits/new")
@SessionAttributes("visit")
public class AddVisitForm {

    private final Clinic clinic;


    @Autowired
    public AddVisitForm(Clinic clinic) {
        this.clinic = clinic;
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields("id");
    }

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(@PathVariable("petId") int petId, Model model) {
        Pet pet = this.clinic.loadPet(petId);
        Visit visit = new Visit();
        pet.addVisit(visit);
        model.addAttribute("visit", visit);
        return "pets/visitForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("visit") Visit visit, BindingResult result, SessionStatus status) {
        new VisitValidator().validate(visit, result);
        if (result.hasErrors()) {
            return "pets/visitForm";
        }
        else {
            this.clinic.storeVisit(visit);
            status.setComplete();
            return "redirect:/owners/" + visit.getPet().getOwner().getId();
        }
    }

}


推荐答案

注意班上的 @SessionAttributes 注释:


  • 当原始 GET 请求到来时,新创建的访问存储在会话中。

  • 当后续的 POST 出现时,会话中存储的对象将使用表单中的输入值进行更新。

  • 访问最终持久化时, status.setComplete()删除会话属性。

  • When the original GET request comes, the newly created Visit is stored in a session.
  • When the subsequent POST comes, object stored in the session is updated with the input values from the form.
  • When Visit is finally persisted, status.setComplete() removes the session attribute.

没有 @SesssionAttributes 访问 POST 到来时,将使用表单输入值重新创建c。

Without @SesssionAttributes, Visit would be recreated using the form input values when POST comes.

这篇关于Spring表单处理,将实体映射到表单输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆