I am writing Web application and trying to integrate Spring Web MVC 3.0 framework. I want to validate input field from XHTML page. The form (what holds one input field) submitted, but then the page is redirected. If you explicitly redirect to the same form (registration.htm) the value entered in the input field disappears, what is not al right. I want the value stay in the input field.
This is my controller:
@Controller
public class UserNameController
{
@InitBinder()
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new UserNameValidator());
}
@RequestMapping(value="userName.htm",method=RequestMethod.POST)
public ModelAndView userName(@Valid @RequestParam("uName") String uName)
{ System.out.println("__________________________ "+ uName);
return new ModelAndView("registration");
}
public class UserNameValidator implements Validator
{
public boolean supports(Class<?> clazz)
{
return User.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors)
{
System.out.println("=======================");
User user = (User) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "uName", "field.required", "Required field");
if(!errors.hasFieldErrors("uName"))
{
// if(user.existUser() == true)
// {
//}
}
}
}
}
Validation does not work either. What is the way to get back on the form what would keep entered value?
Best regards
Do redirect only when you successfully register user, and just return him to registration page when validation fails.
See also: Problems passing form feedback between controllers to re-display a form error message