Validation messages that were not received from the message properties file in Spring

It worked for me yesterday, and then I did something, and now I'm trying to fix it for hours, and I just can't get it to work.

I have a Spring MVC application containing <form:form> that I want to display custom error messages ( <form:errors> ) from a .properties file when the user enters incorrect information. What is โ€œincorrectlyโ€ defined in JSR-303 annotations.

Excerpt from the form:

 <form:form method="post" action="adduserprofile" modelAttribute="bindableUserProfile"> <table> <tr> <td><form:label path="firstName">Voornaam</form:label></td> <td> <form:input path="firstName"/> <form:errors path="firstName" /> </td> </tr> <tr> <td><form:label path="lastName">Achternaam</form:label></td> <td> <form:input path="lastName"/> <form:errors path="lastName" /> </td> </tr> 

Excerpt from BindableUserProfile:

  @NotNull @Size(min = 3, max = 40, message="{errors.requiredfield}") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } @NotNull @Size(min = 3, max = 40, message="errors.requiredfield") public String getLastName() { return lastName; } 

Excerpt from the controller:

  @RequestMapping(value = "/edit/{userProfileId}", method = RequestMethod.GET) public String createOrUpdate(@PathVariable Long userProfileId, Model model) { if (model.containsAttribute("bindableUserProfile")) { model.addAttribute("userProfile", model.asMap().get("bindableUserProfile")); } else { UserProfile profile = userProfileService.findById(userProfileId); if (profile != null) { model.addAttribute(new BindableUserProfile(profile)); } else { model.addAttribute(new BindableUserProfile()); } } model.addAttribute("includeFile", "forms/userprofileform.jsp"); return "main"; } @RequestMapping(value = "/adduserprofile", method = RequestMethod.POST) public String addUserProfile(@Valid BindableUserProfile userProfile, BindingResult result, Model model) { if (result.hasErrors()) { return createOrUpdate(null, model); } UserProfile profile = userProfile.asUserProfile(); userProfileService.addUserProfile(profile); return "redirect:/userprofile"; } 

Excerpt from application-context.xml

  <bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="messages/messages"/> </bean> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="validationMessageSource"> <ref bean="messageSource"/> </property> </bean> 

There are two files in resources / messages: messages_en.properties and messages_nl.properties. Both have the same simple content:

 errors.requiredfield=This field is required!!! 
  • When I submit a form with an empty name, I see in the addUserProfile () controller method that the errors have actually been found.
  • When I submit a form with an empty first name, the message identifier is displayed next to the field, that is, the literal text "errors.requiredfield" or "{errors.requiredfield}" in the case of the last name.
  • When I change the value of the message attribute to "Foo" than "Foo", it displays as an error message. Therefore, the error mechanism itself is working fine.
  • The MessageSource bean from application-context.xml must be correct because it says that it cannot find property files when the base name changes.
  • Empty input is not caught by the NotNull annotation. Spring sees empty input as an empty string, and not as null.

So, it seems that the property files are found, and the validation annotations are processed correctly, but Spring does not understand that it should replace the message keys with messages from the property files.

+4
source share
2 answers

Yaaaargh, I think this should never have worked in the first place.

I thought it was possible for the JSR-303 annotation "message" attribute to be interpreted as a key to get the associated error message from the message.properties file, but I donโ€™t know that I am wrong.

@Size(min = 3, max = 40, message="errors.requiredfield")

My colleague at work programmed a layer that created this behavior for us, but by default it does not work. It seemed that I worked once because I used

@Size(min = 3, max = 40, message="{errors.requiredfield}")

In curly braces, Spring was called to begin the search and replace procedure, which uses the .properties files as the source. This second option still worked.

+3
source

I have been doing the same thing from the past 1.5 days, and finally I found a solution to this.

It may sound a little crazy, but it is a working solution. :)

 @Size(min = 1, max = 50, message = "Email size should be between 1 and 50") 

Now remove message = "Email size should be between 1 and 50" from the validation tag.

After that, your annotation will be like this.

 @Size(min = 1, max = 50) 

Now on the controller side we are debugging the method that is called when the form is submitted. Below is my method, which receives a request when the user enters submit.

 public static ModelAndView processCustomerLoginRequest(IUserService userService, LoginForm loginForm, HttpServletRequest request, HttpSession session, BindingResult result, String viewType, Map<String, LoginForm> model) 

Now place the debug point on the first line of the method and debug the result argument.

 BindingResult result 

During dubugging you will find such a string in an array of codes.

 Size.loginForm.loginId 

Now define this line in the properties file and the message against this line. Compile and execute. This message will be displayed whenever the annotation is not verified.

 Size.loginForm.loginId=email shouldn't be empty. 

Basically, spring makes its own line as the key to the property file message. In the above key:

  • Size(@Size) = check annotation name
  • loginForm = name of my class
  • loginId = name of the property in the loginForm class.

The beauty of this method is also good while you use spring internationalization. It automatically switches the message file with a language change.

+2
source

All Articles