当我在这里阅读explanation时,我发现Spring可以自动将GET请求参数绑定到一个类型。以下是链接中的示例代码。
@Controller
@RequestMapping("/person")
public class PersonController {
...
@RequestMapping("/create")
public String create(Person p) {
//TODO: add Person to DAO
return "person/show";
}
}
有人能告诉我春天是怎么做到的吗?什么bean包含将参数转换为命令类型(Person类型)的逻辑?
答案 0 :(得分:1)
诀窍在这里完成:org.springframework.web.method.annotation.ModelAttributeMethodProcessor#resolveArgument()
这是代码的摘录,它实际上将类绑定到值:
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());
}
}
}