在问这里之前,我在这里搜索了很多,找到了有用的内容,但我无法解决我的问题。
我正在研究 Spring MVC 和 Hibernate Validator 与 i18n 支持的使用。当需要验证表单时,我的问题是相关的,下面是我生成的代码。
豆用户
@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;
}
用户控制器
@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/";
}
用户验证器
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");
}
}
messages.properties 所在位置: 最后是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>
方法执行时报错:
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'.
messages_pt_BR.properties,与 messages.properties 相同:
NotEmpty.user.firstName = Name is required!
好吧,我对此感到疯狂,已经改变了位置,尝试了很多通过网络和春季论坛建立的样本......我感谢任何帮助。
对不起,我的英语不好。