Spring : binding object with and without @ModelAttribute

后端 未结 7 1296
温柔的废话
温柔的废话 2020-12-30 05:47

I am new in Spring and registering a user.I did like this.

@RequestMapping(\"/register\")
    public String register(@ModelAttribute User user,BindingResult          


        
7条回答
  •  隐瞒了意图╮
    2020-12-30 06:51

    There is probably (see below...) no difference in the behaviour between the two method signatures in your case.

    Both will bind the request parameters to user and add the resulting object to the model as the attribute user - this attribute name being derived from the decapitalised type name of the method argument, User.

    @ModelAttribute can be used to customise the name of the attribute, e.g. @ModelAttribute("theUser"), or to give a hint to the reader of your code that this argument is used in the view. But as you say, neither of these apply in your use case.

    Exactly the same code in Spring will be used to populate the argument whether you use the @ModelAttribute annotation or not - the code in question is org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.

    It therefore makes more sense to me for you to use the public String register(User user, BindingResult result) signature in your code. Adding a @ModelAttribute annotation to method arguments that are not required in the model could be confusing to people reading your code.


    The slightly longer answer is that there could just about be a reason for specifying @ModelAttribute in your case - but it's quite arcane and unlikely.

    Method arguments in Spring handler methods are populated by HandlerMethodArgumentResolver instances. These are configurable and are attempted in turn for each parameter.

    The default handler method argument resolvers look like this (see RequestMappingHandlerAdapter):

    resolvers.add(new ServletModelAttributeMethodProcessor(false));
    
    ...
    
    resolvers.add(new ServletModelAttributeMethodProcessor(true));
    

    If you were to add your own in the middle, e.g. a UserHandlerMethodArgumentResolver, you could then use @ModelAttribute to tell Spring to process a specific argument in the default way, rather than use your custom argument resolver class.

提交回复
热议问题