具有ModelAndView的Spring MVCvalidation

我正在尝试为我的Spring MVC应用程序添加validation。 以前尝试设置validation我一直在使用ModelAndView来提供jsp页面但不显示错误消息。

模型

@Entity @Table(name = "employee") public class Employee { @Id @NotEmpty(message = "Please enter your email addresss.") @Email private String email; @NotEmpty @Pattern(regexp="[a-zA-Z0-9]") private String password; @NotEmpty private String firstName; @NotEmpty private String lastName; @NotEmpty private String phoneNum; private boolean assigned; public Employee() { } // getters and setters } 

调节器

 @RestController @RequestMapping("/employee") public class EmployeeController { private static final Logger LOGGER = LogManager .getLogger(EmployeeController.class.getName()); @Autowired private EmployeeServiceImpl employeeService; @RequestMapping(value = "/new", method = RequestMethod.GET) public ModelAndView getRegisterView(Model m) { return new ModelAndView("addEmployee", "employeeForm", new Employee()); } @RequestMapping(value = "/register", method = RequestMethod.POST) public ModelAndView postUser(@Valid Employee employee, BindingResult result) { ModelAndView model; if (result.hasErrors()) { model = new ModelAndView("addEmployee", "employeeForm", employee); } else { employeeService.addEmployee(employee); model = new ModelAndView(); model.setViewName("displayEmployee"); model.addObject("employees", employeeService.getEmployees()); } return model; } } 

形成

 
First Name:
Last Name:
Email:
Phone Number:
Password:

 model = new ModelAndView("addEmployee", "employeeForm", employee); 

您在代码中自己销毁模型,因此返回页面时基本上没有任何东西。 返回ModelAndView Spring MVC假设您已准备好并添加了自己渲染视图所需的所有内容。

而是将@ModelAttribute("employeeForm")添加到@Valid注释旁边的方法参数中,并使用BindingResult已有的模型来构造ModelAndView

 @RequestMapping(value = "/register", method = RequestMethod.POST) public ModelAndView postUser(@Valid @ModelAttribute("employeeForm" Employee employee, BindingResult result) { ModelAndView model; if (result.hasErrors()) { model = new ModelAndView("addEmployee", result.getModel()); 

虽然这可行,但为什么不简单地返回一个String作为视图的名称,并在需要时进行一些Model准备。

 @RequestMapping(value = "/register", method = RequestMethod.POST) public String postUser(@Valid @ModelAttribute("employeeForm") Employee employee, BindingResult result, Model model) { if (result.hasErrors()) { return "addEmployee"; } else { employeeService.addEmployee(employee); model.addObject("employees", employeeService.getEmployees()); return "displayEmployee"; } } 

我甚至认为填充displayEmployee页面的Model不属于此处,而是在为该页面准备模型的单独方法中。