从字段窗体获取对象



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

法典:具有字段的实体用户:

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>返回对象的字符串表示形式,而不是我猜的对象本身。所以我需要找到一种方法来正确地将其发送到/save 控制器。当然,我可以从表单中逐字段获取数据并创建一个新的用户手册,从表单中获取 office.id,而不是向sql发送另一个请求以获取officeById(id),但这似乎是糟糕的编码方式。有人可以帮忙吗?

你需要的是:

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

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

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

最新更新