使用Spring MVC编辑表单验证

时间:2013-04-22 18:41:05

标签: java forms validation spring-mvc

我在项目中使用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的开始状态:没有错误,也没有保存的更改。 我怎么能正确地做到这一点?

谢谢!

1 个答案:

答案 0 :(得分: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");
}