简体   繁体   English

Spring MVC默认GET请求参数绑定到命令类型

[英]Spring MVC default GET request parameter binding to command type

As I read explanation here, I found that Spring can automatically bind GET request parameter to a type. 当我在这里阅读说明时 ,我发现Spring可以自动将GET请求参数绑定到一个类型。 Below is the sample code from the link. 以下是链接中的示例代码。

@Controller
@RequestMapping("/person")
public class PersonController {
        ...             
        @RequestMapping("/create")
        public String create(Person p) {
                //TODO: add Person to DAO
                return "person/show";
        }
}

Can someone tell me how spring do this? 有人可以告诉我这是春天吗? What bean that contains the logic to convert the parameter onto command type (Person type)? 哪个bean包含将参数转换为命令类型(人员类型)的逻辑?

The trick is done here: org.springframework.web.method.annotation.ModelAttributeMethodProcessor#resolveArgument() 窍门在这里完成: org.springframework.web.method.annotation.ModelAttributeMethodProcessor#resolveArgument()

This is the excerpt of code where it actually binds the class to the values: 这是实际上将类绑定到值的代码摘录:

String name = ModelFactory.getNameForParameter(parameter);
//Here it determines the type of the parameter and creates an instance
Object attribute = (mavContainer.containsAttribute(name)) ?
            mavContainer.getModel().get(name) : createAttribute(name, parameter, binderFactory, request);

//Then it binds the parameters from the servlet to the previously created instance
WebDataBinder binder = binderFactory.createBinder(request, attribute, name);
if (binder.getTarget() != null) {
    bindRequestParameters(binder, request);
    validateIfApplicable(binder, parameter);
    if (binder.getBindingResult().hasErrors()) {
        if (isBindExceptionRequired(binder, parameter)) {
            throw new BindException(binder.getBindingResult());
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM