如何从Java代码设置JSTL语言环境? [英] How to set JSTL locale from Java code?
问题描述
我想设置< fmt:formatNumber>
和朋友使用的JSTL语言环境。我知道这可以通过< fmt:setLocale>
来实现,但我需要动态地执行它(取决于从我的数据库中检索的用户数据)并且更喜欢Java代码 - a过滤器类,确切地说。
I want to set the JSTL locale which is used by <fmt:formatNumber>
and friends. I know this is possible with <fmt:setLocale>
, but I need to do it dynamically (depending on user data retrieved from my DB) and would prefer Java code - a filter class, to be precise.
我认为设置会话属性 javax.servlet.jsp.jstl.fmt.locale
到我想要的 Locale
实例可以解决问题,但会被忽略:JSTL标签继续使用浏览器区域设置。
I thought setting the session attribute javax.servlet.jsp.jstl.fmt.locale
to my desired Locale
instance would do the trick, but it is ignored: The JSTL tags keep using the browser locale.
我确认没有相同名称的页面上下文或请求属性。
I verified there are no page context or request attributes of the same name.
那么我做错了什么?或者我真的需要从JSP中做到吗?
So what am I doing wrong? Or do I really need to do it from a JSP?
读取JSTL代码,我发现了对 LocalizationContext的引用
并认为我需要设置一个。我不知道究竟它是如何适应图片或如何设置的。
Reading the JSTL code, I found references to a LocalizationContext
and think I need to set one. I couldn't quite figure out exactly how it fits into the picture or how to set one, though.
推荐答案
你需要第二个:
设置JSTL区域设置的三种方法:
/以及默认的应用程序资源包,时区和数据源/
3 ways to set JSTL locale: /as well as default application resource bundle, time zone, and data source/
-
通过JSTL操作设置 - 这允许通过范围属性指定范围。
Set by a JSTL action – this allows specification of scope by the scope attribute.
<fmt:setLocale value="en_US" scope="session"/>
以编程方式设置 - 允许通过Config API指定范围。
Set Programmatically – allows specification of scope via the Config API.
import javax.servlet.jsp.jstl.core.Config;
(...)
Config.set( session, Config.FMT_LOCALE, new java.util.Locale("en", "US") )
// or Locale.forLanguageTag("en-US") (java 1.7 and later)
由上下文设置初始化参数 - 指定在任何标准范围内找不到设置时使用的值。
Set by Context Initialization Parameters – specifies value used if setting not found in any of the standard scopes.
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.locale</param-name>
<param-value>en_US</param-value>
</context-param>
这篇关于如何从Java代码设置JSTL语言环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!