2013-04-22 100 views
-1

我在我的项目中使用Spring MVC和Spring表单验证。 在对象模型中有一个名为Group的类,我创建了用于编辑它的表单。使用Spring MVC编辑表单验证

<spring:url var="saveGroup" value="/teacher/groups/save"/> 
<form:form action="${saveGroup}" method="post" modelAttribute="group"> 

    <form:hidden path="id"/> 

    <div id="nameDiv" class="control-group"> 
     <form:label path="title">Title:</form:label> 
     <form:input path="title"/> 
     <form:errors path="title"/> 
    </div> 

    <div id="specDiv" class="control-group"> 
     <form:label path="title">Specialty:</form:label> 
     <form:select path="specialty"> 
      <form:options items="${specialties}" itemValue="id" itemLabel="title"/> 
     </form:select> 
    </div> 

    <div class="center"> 
     <spring:url var="groups" value="/teacher/groups"/> 
     <input class="btn btn-primary" type="submit" value="Save"/> 
     <a class="btn" href="${groups}"> Cancel </a> 
    </div> 
</form:form> 

控制器

@Controller 
@RequestMapping("/teacher/groups") 
public class GroupsController { 

    @Autowired 
    private GroupService groupService; 
    @Autowired 
    private SpecialtyService specialtyService; 

    @ModelAttribute("group") 
    public Group setGroup(Long id) { 
     if (id != null) { 
      return groupService.read(id); 
     } else { 
      return new Group(); 
     } 
    } 

    @InitBinder 
    public void initBinder(WebDataBinder binder) { 
     binder.registerCustomEditor(Specialty.class, "specialty", 
      new SpecialtyEditor(specialtyService)); 
     binder.setValidator(new GroupValidator()); 
    } 

    @RequestMapping("") 
    public ModelAndView groups() { 
     return new ModelAndView("teacher/groups/list", "groups", 
      groupService.list()); 
    } 

    @RequestMapping("/edit") 
    public ModelAndView editGroup() { 
     return new ModelAndView("teacher/groups/edit", "specialties", 
      specialtyService.list()); 
    } 

    @RequestMapping(value = "/save", method = RequestMethod.POST) 
    public String saveGroup(@Valid Group group, BindingResult result) { 
     if (result.hasErrors()) { 
      return "forward:/teacher/groups/edit"; 
     } 
     groupService.update(group); 
     return "redirect:/teacher/groups"; 
    } 
} 

我想我的设置形式的适当行为在验证失败的情况。即它应该保存它的状态,但只显示验证错误消息(当使用javascript验证时)。 我以为“forward:/ teacher/groups/edit”会再次将请求转发到editGroup(),并保存了对象groupresult。但是当我验证失败时,只需重新载入并显示已编辑的group的开始状态:没有错误并且没有保存的更改。 我该怎么做才能正确?

谢谢!

回答

0

我解决了问题,因为没有将请求转发给其他方法,而是立即向用户发送答案。现在它的工作原理和外观如下:

@RequestMapping(value = "/save", method = RequestMethod.POST) 
public ModelAndView saveGroup(@Valid Group group, BindingResult result) { 
    if (result.hasErrors()) { 
     return new ModelAndView("/teacher/groups/edit", "specialties", specialtyService.list()); 
    } 
    groupService.update(group); 
    return new ModelAndView("redirect:/teacher/groups"); 
}