简体   繁体   中英

Exclude Spring Controller method from model binding through annotated @ModelAttribute method

I'm getting an invalid request for method getIndex because request parameter id is missing. Can I specify that I don't want model binding for that requestmapping method?

@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";
            }

        }

    }

You could make your id parameter optional

@ModelAttribute("user")
public AdminUser getAdminUser(@RequestParam(value="id", required=false) Integer id) {
    if(id==null){
        return new AdminUser();
    }
    return userService.findAdminById(id);
}

Edit: Or loose the ModelMap paramter:

@RequestMapping (method = RequestMethod.GET)
public ModelAndView getIndex() {
    return new ModelAndView("admin/admins/list", "admins",userService.findAllAdmins());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM