我想知道在某些情况下如何编写“优雅”(或至少正确)的代码: 假设我有一个Spring Controller,它可以像这样将用户插入数据库(从表单):
@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public ModelAndView saveUser(@Valid @ModelAttribute("User") User user, BindingResult result) {
if (result.hasErrors()) {
ModelAndView model = new ModelAndView();
model.setViewName("/user/addUser");
return model;
}
userService.insertUser(user);
}
现在,我想检查 userService.insertUser(user)调用是否顺利,如果是,则返回成功消息,如果不是,则返回错误消息。我是这样写的:
@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public ModelAndView saveUser(@Valid @ModelAttribute("User") User user, BindingResult result) {
if (result.hasErrors()) {
ModelAndView model = new ModelAndView();
model.setViewName("/user/addUser");
return model;
}
if (userService.insertUser(user)) return new ModelAndView("redirect:/users.html?msg="+Msg.UserStatus.USER_INSERT_SUCCESS);
else return new ModelAndView("redirect:/users.html?msg="+Msg.UserStatus.USER_INSERT_ERROR);
}
与用户一起的控制器这样写:
@RequestMapping("/users")
public ModelAndView showUsers(@ModelAttribute("Utenti")Utenti user, @RequestParam(required = false) String msg) {
ModelAndView model = new ModelAndView();
model.addObject("msg", msg);
model.addObject("users", userService.getAllUser());
model.setViewName("/users/users");
return model;
}
这是正确的方法吗?我本能地写出了它,我不知道它是否是正确的操作方式(我从Struts SUCCESS和FAILURE动作结果中得到了启发。)
谢谢