Freemarker and Spring Validation Error Message Doesn't show up error messages - spring

Hi I am working on spring boot 1.5.9.RELEASE and added spring-webmvc (4.3.13.RELEASE) dependency.
When I hit the submit button with some form data, it goes to server and checks if there're some errors, and prints it on console, and return back to form input page. but there is no error messages printed.
I submit the form with ModelAttribute object and the object is defined like below:
#Entity
#Table(name="MEMBER", uniqueConstraints={
#UniqueConstraint(columnNames={"USER_SEQ"}),
#UniqueConstraint(columnNames={"USER_EMAIL"}),
#UniqueConstraint(columnNames={"NICKNAME"})
})
#Data
#NoArgsConstructor
#RequiredArgsConstructor(staticName="of")
public class Member implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="USER_SEQ", unique=true, nullable=false)
private Long userSeq;
#Email
#NotNull
#NonNull
#Column(name="USER_EMAIL", unique=true, nullable=false, length=50)
private String userEmail;
#NotNull
#NonNull
#Column(name="USER_PW", nullable=false, length=255)
private String userPw;
#NotNull
#Size(min=2, max=10)
#NonNull
#Column(name="NICKNAME", unique=true, nullable=false, length=20)
private String nickname;
#OneToOne(mappedBy="member", cascade=CascadeType.ALL)
private MemberSecurity security;
#Override
public String toString() {
return "Member [userSeq=" + userSeq + ", userEmail=" + userEmail + ", userPw=" + userPw + ", nickname="
+ nickname + "]";
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Member other = (Member) obj;
if (userSeq == null) {
if (other.userSeq != null)
return false;
} else if (!userSeq.equals(other.userSeq))
return false;
return true;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((userSeq == null) ? 0 : userSeq.hashCode());
return result;
}
}
In Controller which the submit goes through, I coded like below:
#RequestMapping(value="/join", method=RequestMethod.POST)
public String join(Model model, #Valid #ModelAttribute("join") Member member, BindingResult bindingResult, RedirectAttributes redirect){
if(bindingResult.hasErrors()){
viewNameChooser.joinForm(model);
System.err.println("ERROR COUNT: " + bindingResult.getErrorCount());
System.err.println("ERROR FIELD: " + bindingResult.getFieldError().getField());
System.err.println("ERROR CODE: " + bindingResult.getFieldError().getCode());
return go();
}
redirect.addFlashAttribute("joinSuccess", String.valueOf(memberService.save(member)) );
return "redirect:/member/login-form";
}
and the console output is :
ERROR COUNT: 1
ERROR FIELD: nickname
ERROR CODE: Size
Now I registered my custom error messages in classpath:META-INF/messages.properties:
Email.member.userEmail=It is not email type text.
NotNull.member.userEmail=Please, type your email id.
NotNull.member.userPw=Please, type your password.
NotNull.member.nickname=Please, type your nickname.
Size.member.nickname=The length of nickname must be greater than or equal 2 and less than or equal 10.
So far so good, but in my freemarker template, there is no error message displayed. I have coded like below:
<#assign form=JspTaglibs["http://www.springframework.org/tags/form"] />
<form id="join-form" action="<#spring.url '/member/join' />" method="post" style="width:600px; margin:0 auto;">
<#spring.bind "join" />
<#-- skipped -->
<#form.errors "*" />
<#-- skipped -->
</form>
<#form.errors "*" />
should contain error messages but it's not. Where am I missing? Help me please.
EDIT: I modified my controller method.
#RequestMapping(value="/join", method=RequestMethod.POST)
public ModelAndView join(#Valid #ModelAttribute("join") Member member, BindingResult bindingResult, RedirectAttributes redirect){
if(bindingResult.hasErrors()){
//viewNameChooser.joinForm(bindingResult);
ModelAndView modelAndView = new ModelAndView("template", bindingResult.getModel());
modelAndView.addObject("viewName", "joinForm");;
System.err.println("ERROR COUNT: " + bindingResult.getErrorCount());
System.err.println("ERROR FIELD: " + bindingResult.getFieldError().getField());
System.err.println("ERROR CODE: " + bindingResult.getFieldError().getCode());
return modelAndView;
}
ModelAndView modelAndView = new ModelAndView("redirect:/member/login-form");
redirect.addFlashAttribute("joinSuccess", String.valueOf(memberService.save(member)) );
return modelAndView;
}
Now I am using ModelAndView.

Related

I can't get an entity ID in spring boot

I am learning Spring-Boot and I'm doing a little project to practice, but I have a problem.
This is a simple authentication app, you can register and log in. My aim is: If you log in your username should be appeared, and for further functions I need the ID as well.
So I have this code:
#PostMapping("/main")
public String login(#ModelAttribute Users user, Model model) {
time = sdf.format(new Date());
Users correctUser = serv.selectUser(user.getName(), user.getPassword());
if (correctUser != null) {
//Users data
login_name = user.getName();
actual_user_id = user.getId();
model.addAttribute("given_name", login_name);
System.out.println("DEBUG: " + user);
System.out.println(time + " Successful");
return "main_screen";
} else {
System.out.println(time + " Log in failed");
return "error_page";
}
}
I can get and storage the name well in login_name, but with the ID I have some problems. As you can see I use user.getId() same as with name, but either way I get null and can't storage the ID in my actual_user_id variable.
Here is my repository:
#Repository
public interface UserRepository extends JpaRepository<Users, Integer> {
Optional<Users> findFirstByName(String name);
Optional<Users> findUserByNameAndPassword(String name, String password);
}
And my service method:
public Users authentication(String name, String password) {
return repo.findUserByNameAndPassword(name, password).orElse(null);
}
EDIT: And this is my Users class
#Entity
#Table(name = "users")
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String password;
private String email;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Users{" +
"id=" + id +
", name='" + name + '\'' +
", passowrd='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
}
I think it should work, but I can't find the problem.
Can anyone help me?
As I can see, I get the name and the password with the findUserByNameAndPassword() and nothing else, however I should I suppose.
You look to be trying to get your id from the user passed to you in the post request:
actual_user_id = user.getId();
Try getting your information from the user you retrieved from the database:
actual_user_id = correctUser.getId();

Annotation #AssertTrue is not working properly

My poblem is connected with #AssertTrue annotation and some how with Thymeleaf. Actualy I should scheck password for the equality on a registration web page, for this I hava a parameters in my Registrartion Form class, they are Name,password, check_password,check_password_condition, adress. Actually I have made several changes in y code since I have aske my question here. I have used equals() method instead of == and acording this post
Spring validation #AssertTrue
have set a validation property boolean check_password_condition but my code still does not work. This way I use Errors interface to ask my page for validation rules. I think that using of the annotation #AssertTue for my method sould automatically call my method isCheckpassword() from RegistrationForm class and then in #PostMapping method of the Controller asked for the validation rule this.password.equals(this.check_password)
Am I right or not????
#AssertTrue(message = "{RegistrationForm.check_password.AssertTrue}")
public boolean isCheckpassword(){
if(this.password.equals(this.check_password)){
return this.check_password_condition=true;
}
else return this.check_password_condition=false;
}
#PostMapping("/register")
String registerNew(#Valid RegistrationForm form, Errors result) {
if (result.hasErrors()) {
return "register";
}
customerManagement.createCustomer(form);
return "redirect:/";
}
But I get whitepage error when the conditions for the creating new user are not met.
here additionally I provide my Thymeleaf code:
<div class="field">
<label th:text="#{register.check_password}" for="check_password">Repasswort</label>
<input id="check_password" name="check_password" th:field="*{check_password}" th:errorclass="fieldError" type="password"
required="required"/><br/>
<p th:if="${#fields.hasErrors('check_password')}" th:errors="*{check_password}">Das Passwort darf
nicht leer sein.</p>
</div>
This is my Registration From class
class RegistrationForm {
#NotEmpty(message = "{RegistrationForm.name.NotEmpty}") //
private final String name;
#Size(min = 2, max = 14, message = "{RegistrationForm.password.Size}")
#NotEmpty(message = "{RegistrationForm.password.NotEmpty}") //
private final String password;
#NotEmpty(message = "{RegistrationForm.check_password.NotEmpty}") //
private String check_password;
private boolean check_password_condition;
#NotEmpty(message = "{RegistrationForm.address.NotEmpty}") // s
private final String address;
public RegistrationForm(String name, String password,String check_password, String address) {
this.name = name;
this.password = password;
this.check_password=check_password;
this.address = address;
}
#AssertTrue(message = "{RegistrationForm.check_password.AssertTrue}")
public boolean isCheckpassword(){
if(this.password.equals(this.check_password)){
return this.check_password_condition=true;
}
else return this.check_password_condition=false;
}
//return this.password != null && this.password.equals(this.check_password) : this.setCheck_password(); }
public String getName() {
return name;
}
public String getPassword() { return password; }
public String getCheck_password(){return check_password;}
public String getAddress() {
return address;
}
}
Please help to solve this problem when
error info from Whitelabel errorpage is:
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#fields.hasErrors('*')" (template: "register" - line 29, col 42)
at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:290)
at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166)
at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:125)
It may not fully solve your issue, but looks like your String comparison is incorrect, as you shouldn't use ==.
Instead, use the String#equals() method or even Objects.equals(). This answer provider a great explanation on this.
Here's what your code can be like:
#AssertTrue
public boolean checkPasswod() {
return Objects.equals(check_password, password);
}

How to check response of HTTP GET method using ID

Here is my controller code:
#RequestMapping(value = RestURIConstants.GET_APP_MENU_LIST, method = RequestMethod.GET)
public #ResponseBody ComListMaster getCommonMasterByMasterId(#PathVariable("listid") Integer listId)
{
ComListMaster commonMaster = commonService.getCommonMasterList(listId);
logger.debug("Calling master list");
return commonMaster;
}
Above code give me the exception:
Caused by: java.lang.NumberFormatException: For input string: "{listid}"
Please tell me how to get GET response of above code.
Thanks in advance.
here is ComListMaster
public class ComListMaster extends BaseModel implements java.io.Serializable
{
private static final long serialVersionUID = 5408136749548491686L;
#Id
#Column(name = "LIST_ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer listId;
#Column(name = "LIST_DESC")
private String description;
#Column(name = "LIST_VALUE")
private String value;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "comListMaster")
private Set<ComListDetails> comListDetails = new HashSet<ComListDetails>();
public Integer getListId()
{
return listId;
}
public void setListId(Integer listId)
{
this.listId = listId;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public String getValue()
{
return value;
}
public void setValue(String value)
{
this.value = value;
}
public Set<ComListDetails> getComListDetails()
{
return comListDetails;
}
public void setComClientAddresses(Set<ComListDetails> comListDetails)
{
this.comListDetails = comListDetails;
}
#Override
public String toString()
{
return "ComListMaster [listId=" + listId + ", description=" + description + ", value=" + value
+ ", comListDetails=" + comListDetails + "]";
}
}
My exception is: java.lang.NumberFormatException: For input string: "{listid}"
API: public static final String GET_APP_MENU_LIST = "/api/app/common/master/{listid}";
You can remove ("listid")-its not mandatory , then it wont java.lang.NumberFormatException: For input string: "{}".
#RequestMapping(value = "/{listId}", method = RequestMethod.GET)
public #ResponseBody ComListMaster getCommonMasterByMasterId(#PathVariable Integer listId)
{
ComListMaster commonMaster = commonService.getCommonMasterList(listId);
logger.debug("Calling master list");
return commonMaster;
}
The code you posted is correct.
The error seems to indicate you are trying to go to the /api/app/common/master/{listid} url. Instead you should substitute the {listid} with a real id, for example /api/app/common/master/1

Unable to save model with Many-to-Many relationship: form returns JSF Validation Error: Value is not valid [duplicate]

This question already has answers here:
Validation Error: Value is not valid
(3 answers)
Closed 7 years ago.
I have stayed on this issue for sometimes now. Can someone tell me what I am getting wrong
Groupp.java
public class Groupp implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Basic(optional = false)
#NotNull
private String name;
#Basic(optional = false)
#NotNull
private String description;
#JoinTable(name = "group_role", joinColumns = {
#JoinColumn(name = "group_id", referencedColumnName = "id", nullable = false)}, inverseJoinColumns = {
#JoinColumn(name = "role_id", referencedColumnName = "id", nullable = false)})
#ManyToMany
private List<Role> roles;
//getters and setters
}
GroupController.java
#Named("groupController")
#SessionScoped
public class GroupController implements Serializable {
private Groupp current;
#EJB
private GroupFacade ejbFacade;
public GroupController() {
}
public Groupp getSelected() {
if (current == null) {
current = new Groupp();
selectedItemIndex = -1;
}
return current;
}
public String createGroup() {
System.out.println("********Start Create Group***********");
try {
getFacade.create(current);
return null;
}
#FacesConverter(forClass = Groupp.class)
public static class GrouppControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
System.out.println("Groupp::Submitted: String: "+value);
if (value == null || value.length() == 0) {
return null;
}
GroupController controller = (GroupController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "grouppController");
System.out.println("Groupp::Object of Submitted: String: "+controller.getGroupp(getKey(value)));
return controller.getGroupp(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Groupp) {
Groupp o = (Groupp) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Groupp.class.getName());
}
}
}
}
RoleController.java
#Named("roleController")
#SessionScoped
public class RoleController implements Serializable {
private Role current;
#EJB
private RoleFacade ejbFacade;
public RoleController() {
}
public SelectItem[] getItemsAvailableSelectMany() {
for (Object x : ejbFacade.findAll()) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
}
#FacesConverter(forClass = Role.class)
public static class RoleControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
System.out.println("Role::Submitted: String: "+value);
if (value == null || value.length() == 0) {
return null;
}
RoleController controller = (RoleController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "roleController");
System.out.println("Role::Object of Submitted: String: "+controller.getRole(getKey(value)));
return controller.getRole(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Role) {
Role o = (Role) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Role.class.getName());
}
}
}
}
create.jsp
<f:view>
<h:form id="groupForm">
<h:inputText id="name" value="${groupController.selected.name}" />
<h:inputText id="description" value="${groupController.selected.description}" />
<h:selectManyListbox id="roles" value="${groupController.selected.roles}" >
<f:selectItems value="${roleController.itemsAvailableSelectMany}" var="role" itemValue="${role}" itemLabel="${role.label}" >
</h:selectManyListbox>
<b:commandButton action="${groupController.createGroup}" value="SAVE" />
</h:form>
</f:view>
Each time I click on the SAVE Button i get "groupForm:roles: Validation Error: Value is not valid" and "********Start Create Group***********" is never printed
Could you try it like this instead:
public List<Role> getItemsAvailableSelectMany() {
return roleFacade.findAll();
}
<f:selectItems value="${groupController.itemsAvailableSelectMany}"
var="role"
itemValue="${role}"
itemLabel="${role.xxx}"/>
(whatever property you want shown from role entity in the last line).
Plus the converter is needed, if in doubt this one seems nice.

org.springframework.validation.BeanPropertyBindingResult

Controller class-
#Controller
#SessionAttributes({"id", "roleId"})
#RequestMapping("/User")
public class UserController {
#Autowired
private UserService userv = null;
#InitBinder("stdUser")
private void initBinder(WebDataBinder binder) {
System.out.println("1111======"+binder.getObjectName());
binder.setValidator(new NewUserValidator());
System.out.println("2222======"+binder.getObjectName());
}
#RequestMapping(value = "/allUsers")
public ModelAndView allUser(#ModelAttribute("userSetup")#Valid UserBean stdUser, BindingResult result, Map<String, Object> map, HttpSession session) {
StdCheckAccessV chk = new StdCheckAccessV();
chk.setFexe(Screens.User.substring(Screens.User.lastIndexOf("/") + 1, Screens.User.length()));
chk.setUid(Long.parseLong(session.getAttribute("id").toString().trim()));
chk.setRid(Long.parseLong(session.getAttribute("roleId").toString().trim()));
chk = userv.getAccess(chk);
List<StdUsers> l = userv.getUsersList();
stdUser.setChkAccessV(chk);
map.put("userList", l);
return new ModelAndView(Screens.User);
}
#RequestMapping(value = "/submitUser")
public ModelAndView addOrUpdate(#ModelAttribute("userSetup")#Valid UserBean stdUser, BindingResult result, HttpSession session, final RedirectAttributes redA) {
try {
int res = 0;
Long id = stdUser.getStdUsers().getId();
if (result.hasErrors()) {
System.out.println("///////result has errors " + result.toString());
return new ModelAndView("redirect:/User/allUsers");
}
System.out.println("////////the id============"+id);
if (id == null) {
System.out.println("/////inside the if");
stdUser.getStdUsers().setUserGroupId(Long.parseLong(session.getAttribute("id").toString().trim()));
stdUser.getStdUsers().setCreatedBy(Long.parseLong(session.getAttribute("id").toString().trim()));
stdUser.getStdUsers().setCreationDate(new Date());
res = userv.submitUser(stdUser);
} else {
System.out.println("/////inside the else");
stdUser.getStdUsers().setUpdateDate(new Date());
stdUser.getStdUsers().setUpdatedBy(Long.parseLong(session.getAttribute("id").toString().trim()));
res = userv.updateUser(stdUser);
}
} catch (Exception e) {
System.out.println("////Exception in add or update method " + e);
}
return new ModelAndView("redirect:/User/allUsers");
//return "redirect:/User/allUsers";
}}
Validator class-
#Component
public class NewUserValidator implements Validator {
#Override
public boolean supports(Class<?> userOb) {
return UserBean.class.equals(userOb);
}
#Override
public void validate(Object target, Errors errors) {
try {
UserBean user = (UserBean) target;
if (user.getStdUsers().getUserName() == null) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "stdUsers.userName", "user.name.empty");
//errors.reject("stdUsers.userName", "User Name is mandatory");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Bean Class-
public class UserBean {
private #Valid StdUsers stdUsers;
private #Valid StdCheckAccessV chkAccessV;
private boolean listView = true;
private String rePassword;
getters and setters.... }
index.jsp-
<body>
<%
session.setAttribute("id", 1);
session.setAttribute("roleId", 1);
%>
User<br>
</body>
CMN/STD100002.jsp page
<td class="tdright"><form:label path="stdUsers.userName">User Name<em>*</em></form:label></td>
<td><form:input path="stdUsers.userName"/></td>
<td><form:errors path="stdUsers.userName"></form:errors></td>
<a href="#" name="btnsub" id="btnsub" onclick="submitUser()">
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td width="25" height="24px" align="center">
<img src="${pageContext.servletContext.contextPath}/resources/images/Buttons/gray icon/Add.png" width="16" height="15" border="0" />
</td>
<td>Submit</td>
<td></td>
</tr>
</table>
</a>
<script type="text/javascript">
function submitUser(){
document.form1.action="${pageContext.servletContext.contextPath}/User/submitUser";
document.form1.submit();
}
</script>
I am following a tutorial for using validation in spring as i am new for spring.
On click of the submit button while leaving the User Name field empty, it should get validated with the message from Validator.
When i tried to print the error in controller class by-
System.out.println("result has errors " + result.toString());
it prints-
result has errors org.springframework.validation.BeanPropertyBindingResult: 1 errors
Please help, i am not getting where i am wrong.
I used this code to check where is the error-
for (Object object : result.getAllErrors()) {
if (object instanceof FieldError) {
FieldError fieldError = (FieldError) object;
System.out.println("the field errors::::::::::::::::"+fieldError.getCode());
}
if (object instanceof ObjectError) {
ObjectError objectError = (ObjectError) object;
System.out.println("the object errors:::::::::"+objectError.getCode());
}
}
and i found-
the field errors::::::::::::::::user.name.empty
the object errors:::::::::user.name.empty
///////result has errors org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'userSetup' on field 'stdUsers.userName': rejected value []; codes [user.name.empty.userSetup.stdUsers.userName,user.name.empty.stdUsers.userName,user.name.em pty.userName,user.name.empty.java.lang.String,user.name.empty]; arguments []; default message [null]
Since these two fields i am putting empty to check validation. If i will get these error on putting the fields empty then how can i validate them?
StdUser-
#Entity
#Table(name = "STD_USERS")
#NamedQueries({
#NamedQuery(name = "StdUsers.findAll", query = "SELECT s FROM StdUsers s")})
public class StdUsers implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GenericGenerator(name="generator",strategy="increment")
#GeneratedValue(generator="generator")
#Basic(optional = false)
#Column(name = "ID", nullable = false)
private Long id;
#Basic(optional = false)
#Column(name = "USER_NAME", nullable = false, length = 50)
private String userName;
setters and getters.....
Any one please reply.
Oh finally got the solution just here-
Changed the Validator class as-
try {
UserBean user = (UserBean) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "stdUsers.userName","required.stdUsers.userName" ,"User name required");
} catch (Exception e) {
System.out.println(e);
}
and in Controller class rather than returning to controller's allUsers method when result.hasError() i.e.-
return new ModelAndView("redirect:/User/allUsers");
changed to(navigated to page)-
return new ModelAndView("/CMN/STD100002");
and yes if you are getting date conversion related error, use this in your controller class-
#InitBinder
private void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");//edit for the format you need
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

Resources