Monday, January 28, 2013

SpringMVC displays error message on the same page

This is an example jsp page:


<form:form action="dologin.do" commandName="hello" method="post" id="abc">
<fmt:message key="label.username" />
<form:input path="userName" />
<form:errors path="userName" />
<br />
<fmt:message key="label.password" />
<form:input path="password" />
<form:errors path="password" />
<br />
Date: <input type="text" id="datepicker" />
<br />
<input type="submit" value="submit it" />
<c:out value="${exception}"/>
</form:form>



1) show error message for data validation


@RequestMapping(value = "/dologin.do", method = RequestMethod.POST)
public ModelAndView dologin(@Valid @ModelAttribute("hello") Hello hello,
BindingResult result,HttpSession session) throws Exception {

if (result.hasErrors()) {    // trigger to show validation error
return new ModelAndView("login");
}

try {
accountService.addAccount(hello.getUserName(), hello.getPassword());
} catch (Exception e) {
error(method,"Could not add account:"+hello,e);
throw e;    // remember to throw out exception
}
return new ModelAndView("hello");
}

===== validator =====


@Service
public class TestValidator implements Validator {

public boolean supports(Class<?> cls) {
return com.demo.web.bean.Hello.class.isAssignableFrom(cls);

}

public void validate(Object obj, Errors errors) {

Hello hello = (Hello) obj;
validateUserName(hello, errors);
validatePassword(hello, errors);
}

private void validateUserName(Hello hello, Errors errors) {

if (hello.getUserName() == null
|| hello.getUserName().trim().length() == 0) {

errors.rejectValue("userName", "username.empty");
}
if (hello.getUserName().equalsIgnoreCase("WX")) {

errors.rejectValue("userName", "username.me");
}
}

private void validatePassword(Hello hello, Errors errors) {
if (hello.getPassword() == null
|| hello.getPassword().trim().length() == 0) {

errors.rejectValue("password", "password.empty");
}
}
}

2) show error message if process failure

2.1) in your controller method, you are supposed to throw out the exception


try {
accountService.addAccount(......);
} catch (Exception e) {
error(method,"Could not add account:"+hello,e);
throw e;
}
return new ModelAndView("hello");


2.2) add one more method to handle the exception and give the error message to be shown on the web page.

       @ExceptionHandler( Exception.class )
public ModelAndView handleException( Exception ex ){
ModelAndView mv = new ModelAndView("login","exception","cannot add account info.");
mv.addObject("hello", new Hello());
   return mv;
}


No comments:

Post a Comment