如何使用 Spring 3 的 SessionLocaleResolver 在 JSP 中获取访问者的区域设置
我需要在 JSP 页面中获取访问者的区域设置,以便我可以正确显示带有语言列表的下拉菜单,并根据他们当前的区域设置选择语言。通常我可能会做类似 ${pageContext.request.locale}
的事情。
我认为的问题是,它只会根据用户的请求标头(浏览器发送的内容)为我提供区域设置。但是用户可能已经更改了他们的语言/区域设置,因此我需要使用 Spring 的机制来查看会话:
RequestContextUtils.getLocale(request).toString();
但是在 JSP 页面中访问它并让 JSP 代码使用它并不那么容易。
或者是否有另一种更简单的机制来向用户显示语言下拉菜单? Spring 是否将当前区域设置存储在可从 JSP 轻松访问的对象中?
I need to get a visitor's locale in my JSP pages so that I can properly display a drop down menu with a list of languages and have the selected language according to their current locale. Normally I might do something like ${pageContext.request.locale}
.
The problem, I think, is that will only give me the locale according to the user's request headers (what the browser sends). But the user may have changed their language/locale, so I need to use Spring's mechanism which looks at the session too:
RequestContextUtils.getLocale(request).toString();
But then it's not so easy to access that in a JSP page and have JSP code work with it.
Or is there another easier mechanism to display a drop down menu of languages to a user? Does Spring store the current locale in an object easily accessible from JSP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对我们来说,
成功了。该属性遵循 Spring 的语言环境解析器设置的内容。
For us
did the trick. This property follows what has been set up by Spring's locale resolver.
当您使用 SessionLocaleResolver 时,当前区域设置将使用 SessionLocaleResolver 类中指定的属性名称存储在会话中。对 SessionLocaleResolver 的引用使用另一个属性名称 (org.springframework.web.servlet.DispatcherServlet#LOCALE_RESOLVER_BEAN_NAME) 存储在请求中。
我没有看到在不使用 java 代码的情况下直接在 jsp 页面中获取语言环境的简单方法。
我将获取当前区域设置并在控制器中创建可选语言列表,并将其添加到模型中。
这使得代码可测试并将 java 代码从 jsp 移动到控制器中。
As you use the SessionLocaleResolver the current locale is stored in the session using an attribute name specified in the SessionLocaleResolver Class. The reference to the SessionLocaleResolver is stored in the request using another attribute name (org.springframework.web.servlet.DispatcherServlet#LOCALE_RESOLVER_BEAN_NAME).
I don't see an easy way to get the locale directly within the jsp page without using java code.
I would fetch the current locale and create the list of selectable languages in the controller and add this to the model.
This makes the code testable and moves java code from the jsp into the controller.
一条线解决方案..
One line solution..