-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()
,并保存了对象group
和result
。但是当我验证失败时,只需重新载入并显示已编辑的group
的开始状态:没有错误并且没有保存的更改。 我该怎么做才能正确?
谢谢!