简体   繁体   English

Spring地图如何将数据发布到POJO?

[英]How does spring map post data to POJO?

I have a spring controller defined like this: 我有一个如下定义的弹簧控制器:

@Controller
@RequestMapping("/user")
class UserController {
    ...
    @RequestMapping(method=RequestMethod.POST)
    public String save(User user) {
        // Do something with user
        return "redirect:/...";
    }
}

How is post data (data submitted from a form) mapped to the User object in this case? 在这种情况下,发布数据(从表单提交的数据)如何映射到User对象? Is there any documentation on how this works? 有没有关于它是如何工作的文件?

What happens if I have two POJOs like this? 如果我有两个像这样的POJO会怎么样?

@Controller
@RequestMapping("/user")
class UserController {
    ...
    @RequestMapping(method=RequestMethod.POST)
    public String save(User user, Foo anotherPojo) {
        // Do something with user
        return "redirect:/...";
    }
}

In the first case, Spring MVC will attempt to match the HTTP POST parameter names to the property names of the User class, converting the types of those parameters values as necessary. 在第一种情况下,Spring MVC将尝试将HTTP POST参数名称与User类的属性名称进行匹配,并根据需要转换这些参数值的类型。

In the second case, I believe Spring will throw an exception, since it will only accept one Command object. 在第二种情况下,我相信Spring会抛出异常,因为它只接受一个Command对象。

In many occasions it should be enough if the POST parameter names are the same as you POJO attribute names. 在许多情况下,如果POST参数名称与POJO属性名称相同,则应该足够了。 The proper way though is to use the Spring form taglib and bind it to your pojo: 正确的方法是使用Spring form taglib并将其绑定到你的pojo:

@Controller
@RequestMapping("/user")
class UserController {
    ...

    @RequestMapping(value="/login", method=RequestMethod.GET)
    public ModelAndView get() {
        return new ModelAndView().addObject("formBackingObject", new User());
    }

    @RequestMapping(value="/login", method=RequestMethod.POST)
    public String save(User user) {
        // Do something with user
        return "redirect:/...";
    }
}

And then in your JSP: 然后在你的JSP中:

// e.g in user/login.jsp
<form:form method="post" commandName="formBackingObject" action="/user/login.html">
    <form:label path="username"><spring:message code="label.username" /></form:label>
    <form:input path="username" cssErrorClass="error" />
    <form:label path="password"><spring:message code="label.password" /></form:label>
    <form:password path="password" cssErrorClass="error" />
    <p><input class="button" type="submit" value="<spring:message code="label.login" />"/></p>
</form:form>

You can nest your attributes (eg address.street if your user has an address property), I don't think Spring will accept more than one command object though. 您可以嵌套您的属性(例如,如果您的用户具有地址属性,则为address.street),我不认为Spring会接受多个命令对象。

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

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