oneyoungping
oneyoungping

Reputation: 19

how to do Validation and Exceptions in spring mvc&thymeleaf

I'm using Spring MVC and Thymeleaf and I have read these things: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc https://spring.io/guides/gs/validating-form-input/

1 -- I'm still not know how validate forms without @Valid annotation, like how to do validation in such case (without form-matched 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 -- And how to handle Exceptions like UserNotFoundException and notice user in form rather than response with a new view.

Upvotes: 2

Views: 1148

Answers (3)

Ravi Kavaiya
Ravi Kavaiya

Reputation: 849

1) You need to create one form Class for the data

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) your controller method:

@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";
}   

Your HTML code :

<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> 

Note :

  • Common message append in header if form validation is fail
  • form filed error message append as per your set message in form class

Upvotes: 0

user6123617
user6123617

Reputation:

Try This... im working on better solution

@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;
    }
}

Upvotes: 1

user6123617
user6123617

Reputation:

Throw an exception if you have an error, and then use @ExceptionHandler to annotate another method which will then handle the exception and render the appropriate response.

Upvotes: 1

Related Questions