更好的方式来提供列表框

时间:2012-01-04 15:25:18

标签: java spring spring-mvc

使用ModelAttribute注释,我们可以提供很多像listbox这样的东西。

使用控制器中的不同方法为每个lisbox提供信息或使用表单并为每个列表框添加一个对象列表是否更好?

1 个答案:

答案 0 :(得分:0)

如果控制器类用于不同的请求,其中一些具有此列表框而另一些则没有,(例如,Controller处理show,创建和更新实体的功能,其中只有create和update页面具有该列表框)然后用@ModelAttribute带注释的方法弹出模型意味着,即使不需要值,也会执行此方法。 - 我谦虚的意见,这将是不好的。

我希望我理解你的问题,如果没有,请为你想要比较的两个选择中的每一个添加一个例子。

@RequestMapping("/users")
@Controller
TheWayIPreferController() {

@RequestMapping(params = "form", method = RequestMethod.GET)
public ModelAndView createForm() {
  ModelMap uiModel = new ModelMap();
  uiModel.addAttribute("userCreateCommand", new UserCreateCommand());
  uiModel.addAttribute("securityRoles", this.securityRoleDao.readAll()));
  uiModel.addAttribute("salutations", this.salutationDao.readAll()));
  uiModel.addAttribute("locales", this.localeDao.readAll());
  return new ModelAndView("users/create", uiModel);
}

@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(final @Valid UserCreateCommand userCreateCommand, final BindingResult bindingResult) {
...
}


@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ModelAndView show(@PathVariable("id") final User user) {
...
}
}

而不是:

@RequestMapping("/users")
@Controller
TheWayIDiscourageController(){


@ModelAttribute("securityRoles")
public List<SecurityRoles> getSecurityRoles(){
   return this.securityRoleDao.readAll();
}

@ModelAttribute("salutations")
public List<SecurityRoles> getSalutations(){
   return this.salutationDao.readAll());
}

@ModelAttribute("locales")
public List<SecurityRoles> getLocals(){
   return this.localeDao.readAll();
}

@RequestMapping(params = "form", method = RequestMethod.GET)
public ModelAndView createForm() {
  return new ModelAndView("users/create", "userCreateCommand", new UserCreateCommand());
}

@RequestMapping(method = RequestMethod.POST)
public ModelAndView create(final @Valid UserCreateCommand userCreateCommand, final BindingResult bindingResult) {
...
}

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ModelAndView show(@PathVariable("id") final User user) {
...
}
}