gpt4 book ai didi

java - 通过带注释的 @ModelAttribute 方法从模型绑定(bind)中排除 Spring Controller 方法

转载 作者:行者123 更新时间:2023-12-01 14:52:08 30 4
gpt4 key购买 nike

我收到对方法 getIndex 的无效请求,因为缺少请求参数 ID。我可以指定我不希望该请求映射方法进行模型绑定(bind)吗?

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

}

}

最佳答案

您可以将 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());
}

关于java - 通过带注释的 @ModelAttribute 方法从模型绑定(bind)中排除 Spring Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14737116/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com