我在我的项目中使用 Spring MVC 和 Spring 表单验证。对象模型中有一个类命名Group
,我创建了用于编辑它的表单。
形式
<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 验证时)。我认为“转发:/teacher/groups/edit”将再次将请求转发到editGroup()
保存的对象group
和result
. 但是当我验证表单失败时,只是重新加载并显示已编辑的开始状态group
:没有错误,也没有保存的更改。我怎样才能正确地做到这一点?
谢谢!