我收到方法getIndex的请求无效,因为缺少请求参数id。我是否可以指定我不希望该请求映射方法的模型绑定?
@Controller
@RequestMapping ("/admin/admins")
public class AdminUserController {
@RequestMapping (method = RequestMethod.GET)
public String getIndex(ModelMap model) {
model.addAttribute("admins",userService.findAllAdmins());
return "admin/admins/list";
}
@ModelAttribute("user")
public AdminUser getAdminUser(@RequestParam("id") Integer id) {
return userService.findAdminById(id);
}
@RequestMapping (method = RequestMethod.POST)
public String registerAdmin(@Valid @ModelAttribute("user") AdminUser user, BindingResult bindingResult, ModelMap model) {
model.addAttribute("roles", userRoleService.findAll());
if (bindingResult.hasErrors()) {
return "admin/admins/form";
}
else if (!user.getPassword().equals(user.getConfirmPassword())) {
bindingResult.addError(new FieldError("user","confirmPassword", "Passwords don't match"));
return "admin/admins/form";
}
else {
user.setPassword(passwordEncoder.encodePassword(user.getPassword(), null));
try {
userService.save(user);
return "redirect:/admin/admins";
} catch(ApplicationException ce) {
bindingResult.addError(new FieldError("user", "email", "Email already registered"));
return "admin/admins/form";
}
}
}
答案 0 :(得分:1)
您可以将您的id参数设为可选
@ModelAttribute("user")
public AdminUser getAdminUser(@RequestParam(value="id", required=false) Integer id) {
if(id==null){
return new AdminUser();
}
return userService.findAdminById(id);
}
编辑:或松开ModelMap参数:
@RequestMapping (method = RequestMethod.GET)
public ModelAndView getIndex() {
return new ModelAndView("admin/admins/list", "admins",userService.findAllAdmins());
}