更改struts2的默认语言环境

问题描述 投票:0回答:2
struts2 internationalization locale
2个回答
2
投票

我知道这是迟到的答案,但有一天有人会发现这是他或她长期以来一直在寻找的东西。

Struts2 框架根据浏览器的语言偏好设置默认区域设置,也就是说,它会查看

Accept-language
请求标头,如果没有找到,则转到 struts 属性进行查找。

因此,如果您想更改为 en_US 语言环境,那么您应该在浏览器参数中进行设置,设置为第一首选语言。

如果你想改变这种行为,你可以编写拦截器来为 ActionContext 设置所需的区域设置。 这里参考API

http://struts.apache.org/maven/struts2-core/apidocs/com/opensymphony/xwork2/ActionContext.html#setLocale(java.util.Locale)
不要忘记将您的拦截器放入 struts.xml 文件中的拦截器堆栈中。

有关创建自己的拦截器的教程:

http://www.tutorialspoint.com/struts_2/struts_interceptors.htm

希望,它会对某人有所帮助。


1
投票

添加到 Yan Pak 的答案,使用以下自定义拦截器对区域设置进行硬编码,忽略 Struts 尝试根据浏览器的

Accept-Language
标头执行的操作。

import java.util.Locale;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class USLocaleInterceptor implements Interceptor {
  private static final long serialVersionUID = 1L;

  @Override
  public void destroy() { }

  @Override
  public void init() { }

  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    invocation.getInvocationContext().setLocale(Locale.US);
    return invocation.invoke();
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.