@ModelAttribute and abstract class

后端 未结 1 477
醉酒成梦
醉酒成梦 2021-01-16 13:18

I know that there have been similar questions. The examples given in them are too fragmentary and unclear.

I need to edit the entities through a form on the page tha

相关标签:
1条回答
  • 2021-01-16 13:45

    You just need to ensure that the element below

    <input type="hidden" value="${person.role}" name="person_type" />
    

    has its named attribute changed to person

    <input type="hidden" value="${person.role}" name="person" />
    

    so that it matches the model attribute in your controller

    public String editPersonPost (@PathVariable Integer personId,
            @Valid @ModelAttribute ( "person") Person person,
            BindingResult result)
    

    This is how it works.

    When a request is received and Spring needs to create the model attribute it checks if the attribute already exists. If it doesn`t exist and there is no request parameter of matching name it creates a new object using the default constructor of the parameter class

    If it exists and matches the argument type it proceeds to bind the request parameters. If it is not compatible or a request parameter of same name is available it tries to find a converter capable of converting the current value to the required type

    If conversion is successful it binds the request parameters to the result otherwise it throws an Exception

    In your case the person attribute is sent as a String. Spring will attempt to convert it to a Person. It picks your PersonConverter to do the conversion to an appropriate subclass before binding

    0 讨论(0)
提交回复
热议问题