从字段表单中获取对象

Getting object from field form

问题:从字段中获取对象作为参数。

代码: 具有以下字段的实体用户:

Long id;
String name;
Office office;

具有字段的实体办公室:

Long id;
String name;

newuser.vm

<title>NEW USER</title>
<body>
<form method="post" action="/save" property="user">  
    Name:
    <input type="text" name="name" path="name"/>    <br>

    Office:
    <select name="office" path="office">
        #foreach($office in $offices)
            <option value="$office">$office.name</option>
        #end
    </select>    <br>
    <input type="submit" value="SAVE"/>
</form>
</body>

和控制器

@Controller
public class ViewController {

    @Autowired
    private UserService userService;
    @Autowired
    private OfficeService officeService;

@RequestMapping(value = "/newuser", method = RequestMethod.GET)
    public ModelAndView newuser(){

        return new ModelAndView("fragments/newuser.vm","command",new User());
    }
@RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView save(@ModelAttribute("user") User user){

        userService.create(user);
        return new ModelAndView("redirect:/list");
    }
//Model Attributes
    @ModelAttribute
    public void userTypesList(Model model){
        model.addAttribute("types", userService.getPositions());
    }
    @ModelAttribute
    public void officesList(Model model){
        model.addAttribute("offices", officeService.getAll();
}

因此,在提交结果中,我必须让新用户将 Office 作为其字段之一。但是我猜 <option value="$office">$office.name</option> returns 是对象的字符串表示,而不是对象本身。所以我需要找到一种方法来正确地将其发送到 /save 控制器。 当然,我可以从表单中逐个字段地获取数据,然后手动创建一个新用户,从表单中获取 office.id,而不是向 sql 发送另一个请求以获取 officeById(id),但这似乎是不好的编码方式。 有人可以帮忙吗?

您需要的是:

<option value="$office.id">$office.name</option>

这就是 ID 字段的用途。提交表单时只有 office id 会被传回,这就是您在创建新用户时向 office table 填充连接所需的全部内容。

$office 显示整个对象的字符串表示形式(即其 toString() 方法)是预期的行为。