Spring : binding object with and without @ModelAttribute

后端 未结 7 1297
温柔的废话
温柔的废话 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:32

    As described in the Spring MVC documentation - the @ModelAttribute annotation can be used on methods or on method arguments. And of course we can have both use at the same time in one controller.

    Method annotation

    @ModelAttribute("person")
    public Person getPerson(){
        return new Person();
    }
    

    Purpose of such method is to add attribute in the model. So in our case person key will have person object as value in the Model. @ModelAttribute methods in a controller are invoked before @RequestMapping methods, within the same controller.

    Method Argument

    public String processForm(@ModelAttribute("person") Person person){
        person.getStuff();
    }
    

    See spring documentation http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-method-args

    0 讨论(0)
  • 2020-12-30 06:36

    Apart from adding object to Model, Spring MVC uses it to supply the bound object to a Controller method where you can use it, in your case to "register".

    And yes @ModelAtttribute is the safest and best way in Spring MVC to bind incoming post data to an object.

    0 讨论(0)
  • 2020-12-30 06:37

    This question is very useful, but I don't see the reply here answer the question properly.

    I read through more threads in stackoverflow, and found this one very useful: https://stackoverflow.com/a/26916920/1542363

    For myself how to decide which one to use, if I only need the binding and do not want to store the parameter object in model, then don't use @ModelAttribute.

    0 讨论(0)
  • 2020-12-30 06:46

    Check this post here. It covers a good amount of details on ModelAttribute.

    ModelAttribute can only be used with form-encoded request data. It cannot bind json/xml request data with the data objects. For that, you will have to use RequestBody.

    0 讨论(0)
  • 2020-12-30 06:48

    in addition to @ryanp 's perfect answer, I'd like to add:

    for modern spring mvc project, it's most certain one would use annotations like @Controller and @RequestMapping etc to provide a request handler, internally, Spring MVC uses RequestMappingHandlerAdapter.invokeHandlerMethod() to process the request with the user provided HandlerMethod. if you look at RequestMappingHandlerAdapter, it sets up a collection of argument resolver to prepare the argument for the HandlerMethod, by looking at the set, you understand how and in what order does Spring MVC parse request and populate the user provided arguments. so here's the source code:

    ```Java

    /**
     * Return the list of argument resolvers to use including built-in resolvers
     * and custom resolvers provided via {@link #setCustomArgumentResolvers}.
     */
    private List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers() {
        List<HandlerMethodArgumentResolver> resolvers = new ArrayList<HandlerMethodArgumentResolver>();
    
        // Annotation-based argument resolution
        resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false));
        resolvers.add(new RequestParamMapMethodArgumentResolver());
        resolvers.add(new PathVariableMethodArgumentResolver());
        resolvers.add(new PathVariableMapMethodArgumentResolver());
        resolvers.add(new MatrixVariableMethodArgumentResolver());
        resolvers.add(new MatrixVariableMapMethodArgumentResolver());
        resolvers.add(new ServletModelAttributeMethodProcessor(false));
        resolvers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice));
        resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters(), this.requestResponseBodyAdvice));
        resolvers.add(new RequestHeaderMethodArgumentResolver(getBeanFactory()));
        resolvers.add(new RequestHeaderMapMethodArgumentResolver());
        resolvers.add(new ServletCookieValueMethodArgumentResolver(getBeanFactory()));
        resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory()));
        resolvers.add(new SessionAttributeMethodArgumentResolver());
        resolvers.add(new RequestAttributeMethodArgumentResolver());
    
        // Type-based argument resolution
        resolvers.add(new ServletRequestMethodArgumentResolver());
        resolvers.add(new ServletResponseMethodArgumentResolver());
        resolvers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice));
        resolvers.add(new RedirectAttributesMethodArgumentResolver());
        resolvers.add(new ModelMethodProcessor());
        resolvers.add(new MapMethodProcessor());
        resolvers.add(new ErrorsMethodArgumentResolver());
        resolvers.add(new SessionStatusMethodArgumentResolver());
        resolvers.add(new UriComponentsBuilderMethodArgumentResolver());
    
        // Custom arguments
        if (getCustomArgumentResolvers() != null) {
            resolvers.addAll(getCustomArgumentResolvers());
        }
    
        // Catch-all
        resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), true));
        resolvers.add(new ServletModelAttributeMethodProcessor(true));
    
        return resolvers;
    }
    

    ```

    What's worth noted is the Catch-all resolvers at the bottom. Spring MVC uses the very same two resolvers that handle @RequestParam and @ModelAttribute to handle non-annotated simple types and pojo types arguments respectively. That's why in OP's test, it doesn't matter if there's @ModelAttribute or not.

    It's a shame that it's not made crystal clear in the Spring MVC's reference.

    0 讨论(0)
  • 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.

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