在Spring MVC中将控制器的错误返回到视图

时间:2012-08-07 12:05:43

标签: spring-mvc

在Spring MVC中,我有以下控制器:

@RequestMapping(value="adminUsers", method = RequestMethod.POST) 
public ModelAndView listAdminUsers(Person newPerson,  HttpServletResponse response)  throws Exception {
Person person = personService.findPerson(newPerson.getUsername());
if (person == null) {
    // Set errorText = "Invalid Person";
    // redisplay view
    ModelAndView mav = new ModelAndView("adminUsersList");
    return mav;
} else {
    Roles roles = new Roles();
    roles.setPersonCode(person.getPersonCode());
    roles.setRoleType("ADMN");
    rolesMapper.insert(roles);
    return new ModelAndView("redirect:/admin/adminUsers.html");
} 
}

有了观点:

    <form:form method="post" action="${action}" commandName="person" >
    <form:label path="username">Add new administrator:</form:label>
    <form:input path="username" size="20"/>
    <form:errors path="username" />
    <input type="submit" value="Submit Changes"/> </form:form>

如何将错误返回给视图,以便<form:errors path="username" />标记显示?

这与How to return error status and validation errors from this Spring MVC controller?类似,除了我正在返回一个网页,而不是一个REST对象,因此那里的答案不适用。

我不想使用Validator,因为上面调用了数据库,它不仅仅是检查用户名是否为空等等。

谢谢!

3 个答案:

答案 0 :(得分:2)

BindingResult添加到您的方法签名中。从那里bindingResult.rejectValue("username", "username.notvalid", "Username is not valid");

答案 1 :(得分:0)

BrandonV拥有它。我的控制器现在看起来像:

  // Create a new item
@RequestMapping(value="adminUsers", method = RequestMethod.POST)
public ModelAndView listAdminUsers(Person newPerson,  BindingResult result, HttpServletResponse response)  throws Exception {
    Person person = personService.findPerson(newPerson.getUsername());
    if (person == null) {
        result.rejectValue("username","username.notvalid","Username doesn't exist");
        ModelAndView mav = new ModelAndView("adminUsersList");  //This is ugly, it's copy & pasted from above
        mav.addObject("adminUsersList", adminService.findAllAdminUsers()); //Ugly...
        return mav;
    } else {
        Roles roles = new Roles();
        roles.setPersonCode(person.getPersonCode());
        roles.setRoleType("ADMN");
        rolesMapper.insert(roles);
        return new ModelAndView("redirect:/admin/adminUsers.html");
    }
}

答案 2 :(得分:0)

您需要更改方法逻辑:

  

if(result.hasErrors){   返回&#34;&#34 ;;   } else {   创建你的人物对象逻辑就在这里!   }