0

我收到对方法 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";
            }

        }

    }
4

1 回答 1

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());
}
于 2013-02-06T19:42:37.567 回答