Monday, 19 August 2013

Hibernate @Valid and Spring MVC

Hibernate @Valid and Spring MVC

Before asking here, I googled and search here a lot, find a usefull
content, but I could not solve my problem.
I´m studing the use of Spring MVC and Hibernate with i18n support. My
problem is related when the form needs to be validated, below is the code
I generated.
Bean User
@Entity(name="users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
private Long id;
@NotEmpty
private String firstName;
private String lastName;
}
UserController
@Secured("ROLE_USER")
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String doSave(@ModelAttribute("formUsuario") @Valid
br.com.rodrigoferra.domain.User user, BindingResult results, Model model)
{
UserValidator userValidator = new UserValidator();
userValidator.validate(user, results);
if(results.hasErrors()) {
return "users/edit";
}
user = userService.create(user);
return "redirect:/users/";
}
UserValidator
public class UserValidator implements Validator {
@Autowired private MessageSource messageSource;
protected static Logger logger = Logger.getLogger("controller");
public boolean supports(Class<?> clazz) {
return User.class.equals(clazz);
}
public void validate(Object target, Errors errors) {
logger.info("Entrou em validate");
User user = (User) target;
if (user.getFirstName() == null) {
errors.rejectValue("firstName", "NotEmpty.user.firstName");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName",
"NotEmpty.user.firstName");
}
}
The location where messages.properties is located: Finally, the
applicationContext.xml
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames"
value="classpath:/resources/i18n/messages,
classpath:/resources/i18n/errors" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean name="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource">
<ref bean="messageSource" />
</property>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.FixedLocaleResolver">
<property name="defaultLocale" value="pt_BR" />
</bean>
The error reported when the method is executed:
GRAVE: Servlet.service() for servlet [spring] in context with path
[/simpla-spring-version] threw exception [Request processing failed;
nested exception is org.apache.tiles.request.render.CannotRenderException:
ServletException including path '/WEB-INF/layouts/simpleLayout.jsp'.] with
root cause
org.springframework.context.NoSuchMessageException: No message found under
code 'NotEmpty.user.firstName' for locale 'pt_BR'.
Well, I´m getting crazy with it, already changed the location, tryed a lot
of samples founded over the web and spring forum... I appreciate any help.
Sorry for my bad english.

No comments:

Post a Comment