如何在春季mvc& thymeleaf中进行验证和例外

时间:2016-03-28 07:06:22

标签: java spring validation spring-mvc thymeleaf

我使用的是Spring MVC和Thymeleaf,我读过这些东西: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc https://spring.io/guides/gs/validating-form-input/

1 - 我还不知道如何在没有@Valid注释的情况下验证表单,比如在这种情况下如何进行验证(没有形式匹配的bean)

@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String registrationSubmit(@RequestParam(required = false) String phone,
                                 @RequestParam(required = false) String passwd,
                                 @RequestParam(required = false) String passwdRepeat,
                                 @RequestParam(required = false) String smsCode, BindingResult bindingResult) {
    //validation
    if (phone.isEmpty()) {
        FieldError fieldError = new FieldError("phone","phone","phone error");
        bindingResult.addError(fieldError);
        bindingResult.rejectValue("phone", "error.user", "phone error");
        return "register_form";
    }

    return "";
}

2 - 以及如何处理UserNotFoundException之类的例外情况并注意表单中的用户,而不是使用新视图进行回复。

3 个答案:

答案 0 :(得分:1)

如果出现错误则抛出异常,然后使用@ExceptionHandler注释另一个方法,该方法将处理异常并呈现相应的响应。

答案 1 :(得分:1)

试试这个...... 我致力于更好的解决方案

@RequestMapping(method = POST)
@ResponseBody
public FooDto create(@Valid FooDTO fooDto, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return null; // what to do here?
                     // how to let the client know something has gone wrong?
    } else {
        fooDao.insertFoo(fooDto); // What to do if an exception gets thrown here?
                                  // What to send back to the client?
        return fooDto;
    }
}

答案 2 :(得分:0)

1)您需要为数据创建一个表单类

public class UserForm implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @NotBlank(message = "Message Text")
    private String userName;

    @NotBlank(message = "Message Text")
    private String passoword;

    // your other filed with getter and seter 

    ...........................     
}

2)你的控制器方法:

@RequestMapping(value = "/signup", method = RequestMethod.GET)
public String create(Model  model) {
    model.addAttribute("userForm" , new UserForm());
    return "signup";
}
@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String create(@Valid @ModelAttribute UserForm userForm,Errors errors, RedirectAttributes ra, Model  model) {
        if (errors.hasErrors()) {
            return "signup";
        }   
        userService.createUser(userForm);
        return "signup";
}   

您的HTML代码:

<form role="form" th:action="@{/signup}" method="post" th:object="${userForm}">
    <div class="row">
        <div class="col-lg-12">
            <th:block th:if="${#fields.hasErrors('${userForm.*}')}">
                <div th:utext="Common error message">Alert</div>
            </th:block>

            <div class="form-group input-group" th:classappend="${#fields.hasErrors('userName')}? 'has-error'">
                <input type="text" th:field="*{userName}" class="form-control" placeholder="Username" />
                <span class="help-block" th:if="${#fields.hasErrors('userName')}" th:errors="*{userName}">Incorrect title</span>    
            </div>

            // your other filed with submit button          
        </div>
    </div>
</form> 

注意:

  • 如果表单验证失败,则在标题中附加公共消息
  • 表单提交的错误消息根据您在表单类
  • 中设置的消息附加