問題:從字段中獲取對象作爲參數。從字段形式獲取對象
代碼: 實體用戶與字段:
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();
}
因此,在submition的結果中,我必須獲得與Office作爲其領域之一的新用戶。但<option value="$office">$office.name</option>
返回對象的字符串表示,但不是我猜想的對象本身。所以我需要找到一種方法來正確地將其保存到/ save控制器。 Ofcourse我可以從表單中獲取字段數據,並創建一個新的用戶手動從表單獲取office.id,然後再發送另一個請求到sql以獲取officeById(id),但這似乎是不好的方式編碼。 任何人都可以提供幫助嗎?
這不是一個答案,而是一個問題,爲什麼你仍然在使用表單? :o意思是你認真嗎? –
我只是在探索,所以我正在使用我可以獲得的一些信息。如果你有更好的解決方案可以隨時告訴我,我會很高興地看看其他的東西,如果它能幫助我更好/更容易/更快地編碼。 – Vampirenostra
而不是研究已經討厭的方式,你可以首先學習簡單的Ajax調用,不要緊緊地將你的後端和前端與這種方法耦合。 您已經處於學習階段,所以我建議從Spring MVC和Angular 2開始。基本知識從簡單的jQuery開始ajax調用通過ajax發送和檢索數據,然後一旦您瞭解生命週期並開始熟悉這種方法因爲您已經學習了Spring MVC,所以請跳到Angular2。祝你好運:) –