Spring MVC:从控制器方法内获取本地化消息的更好方法?
我有一个 Spring 控制器,它需要在请求范围内设置一条消息,并由于错误而将用户发送回表单。这是方法签名:
public String update(HttpServletRequest request,
Model model,
@ModelAttribute("command") User user,
BindingResult result, SessionStatus status)
在请求对象可用的方法中,这是我在请求范围内设置消息的方法,我觉得这很复杂。
.....
WebApplicationContext ctx = RequestContextUtils.getWebApplicationContext(reque st);
Locale locale = RequestContextUtils.getLocale(request);
request.setAttribute("formError", ctx.getMessage("errors.unique.value", new Object[]{new DefaultMessageSourceResolvable(new String[]{"label.userName"})}, locale));
.......
我的问题如下:
以上设置消息的方式是否正确?
有更好或更简单的方法吗?
感谢您的帮助!
I have a Spring controller it needs to set a message in the request scope and sends the user back to a form because of errors. Here is the method signature:
public String update(HttpServletRequest request,
Model model,
@ModelAttribute("command") User user,
BindingResult result, SessionStatus status)
In the method the request object is available, here is my way of setting a message in the request scope, which I feel is convoluted.
.....
WebApplicationContext ctx = RequestContextUtils.getWebApplicationContext(reque st);
Locale locale = RequestContextUtils.getLocale(request);
request.setAttribute("formError", ctx.getMessage("errors.unique.value", new Object[]{new DefaultMessageSourceResolvable(new String[]{"label.userName"})}, locale));
.......
Here are my questions:
Is the above way correct for setting a message?
Is any better or simpler way?
Thanks for help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否想向用户提供反馈?那么你应该看看
result.rejectValue(field, property)
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/validation/Errors.html#rejectValue%28java.lang.String,%20java.lang.String %29
示例:
如果验证未通过的字段名为“
new_password
”,并且语言属性名为“new_passwort_invalid
”那么你可以这样处理它:greets
Are you trying to give a feedback to the user? Then you should have a look at
result.rejectValue(field, property)
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/validation/Errors.html#rejectValue%28java.lang.String,%20java.lang.String%29
Example:
if the field on which the validation didnt passed is called "
new_password
" and the language property is named "new_passwort_invalid
" then you could handle it like this:greets
(即使帖子很旧,我希望这对其他人有用)
在 servlet-context.xml 配置中,我们声明 bean:
然后在控制器中,我们自动装配 messageSource:
最后,在操作中,我们可以使用区域设置(通过添加区域设置形式参数和使用消息):
(Even if the post is old, I hope this can be useful for others)
In servlet-context.xml configuration we declare the bean:
Then in controller we autowire the messageSource:
Finally in the action we can use the locale (by adding the locale formal parameter and using the message):