嗨,我有一些Ajax Forms
,我在其中使用Async POST
将数据发送到服务器...
如果BindingResult
出现错误,我想在输入字段后的视图中显示一条消息,以解释该错误,因此这是我控制器中的方法:
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public Map<String, String> create(@Valid MyClass myClass, BindingResult bindingResult, Model uiModel,
HttpServletRequest httpServletRequest, HttpServletResponse response, Locale locale) {
if (bindingResult.hasErrors()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
Map<String, String> errorFields = new HashMap<String, String>();
for(FieldError fieldError : bindingResult.getFieldErrors()){
errorFields.put(fieldError.getField(), fieldError.getDefaultMessage());
}
return errorFields;
}
uiModel.asMap().clear();
myService.create(personale);
return null;
}
它可以工作,但是
fieldError.getDefaultMessage()
返回英文消息,但是我想返回本地化消息。我知道我可以这样做:
@NotNull(message="{myMessage}")
private Field field;
但是我不会在每个字段中指定本地化的消息,也许我可以使用
message.properties
文件吗?可能吗??
谢谢!
编辑
我读了这篇文章:another question about my problem,但是我无法从消息中获取信息...
最佳答案
我遇到了同样的问题,我可以这样解决:
在src下定义属性消息(mybasename_locale.properties)
在配置文件(dispatcher-servlet.xml)中包括这些元素,以便正确初始化与Spring相关的类l18n
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>mybasename</value>
</property>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale">
<value>es</value>
</property>
在控制器中,获取对ResourceBundleMessageSource bean的引用。
@Autowired
private ResourceBundleMessageSource mensajes;
然后,您可以通过getMessage方法getMessage(MessageSourceResolvable arg0,Locale arg1)获得错误消息。
@RequestMapping(path = "/login", method=RequestMethod.POST)
@ResponseBody
public ResponseEntity<Validacion> login(@Valid @RequestBody LoginUsuario login_usuario, BindingResult result) {
if (result.hasErrors())
{
System.out.println("HAY ERRORES");
System.out.println(mensajes.getMessage(result.getFieldError(), LocaleContextHolder.getLocale()));
}