如何从JSP访问Locale?

Ser*_*Amo 13 jsp struts locale

我想根据当前Locale的值包含一个js文件.我试图从JSP访问它如下:

<%@ page import="java.util.Locale" %>  
<% if( ((Locale) pageContext.getAttribute("org.apache.struts.action.LOCALE",PageContext.REQUEST_SCOPE)).getLanguage().equals("de")) { %>
    <script src="../themes/administration/js/languages/i18nDE.js" type="text/javascript"> </script>
<% } else { %>
    <script src="../themes/administration/js/languages/i18nEN.js" type="text/javascript"> </script>
<% } %>
Run Code Online (Sandbox Code Playgroud)

但是,我得到一个java.lang.NullPointerException,因为 pageContext.getAttribute("org.apache.struts.action.LOCALE",PageContext.REQUEST_SCOPE)NULL.

有谁知道我怎么能解决这个问题?

daw*_*wez 18

目前我正在使用这个:

<c:set var="localeCode" value="${pageContext.response.locale}" />
Run Code Online (Sandbox Code Playgroud)

以后可以通过使用来访问 ${localeCode}

  1. Scriplet模式,气馁!请参阅为何不使用Scriptlet而不使用scriptlet.

localeCode变量可以查询一个内部的scriptlet用:

<%
  Object ob_localeCode = pageContext.getAttribute("localeCode");
  if (ob_localeCode != null) {
    String currentLanguageCode = (String) ob_localeCode;
  }
  //more code
%>
Run Code Online (Sandbox Code Playgroud)
  1. Scripletless模式正确的方法去.请参阅如何避免JSP文件中的Java代码?在这里SO.

我目前正在使用spring 2.5配置.

所以,在此之后,回到原来的问题,您可以实现以下内容:

<c:set var="localeCode" value="${pageContext.response.locale}" />
<c:choose>
  <c:when test="$localecode == 'de' }"> 
    <script src="../themes/administration/js/languages/i18nDE.js" type="text/javascript"> </script>
  </c:when>
  <c:otherwise>
    <script src="../themes/administration/js/languages/i18nEN.js" type="text/javascript"> </script>
  </c:otherwise>
</c:choose>
Run Code Online (Sandbox Code Playgroud)

或者如果您真的想使用一些简短的代码来打动您的同事,您可以:

<c:set var="localeCode" value="${fn:toUpperCase(pageContext.response.locale)}" />
<c:set var="availLanguages" value="EN,DE" />
<c:if test="${!fn:contains(availLanguages,localeCode)}">
  <c:set var="localeCode" value="EN" />
</c:if>

<script src="../themes/administration/js/languages/i18n{$localeCode}.js" type="text/javascript"> </script>
Run Code Online (Sandbox Code Playgroud)


小智 5

在Struts2中尝试

<s:if test="#request.locale.language=='us'">
     <s:select name="gender" list="#{'M':'Male','F':'female'}" ></s:select>
 </s:if>
Run Code Online (Sandbox Code Playgroud)


Ken*_*tle 2

org.apache.struts.action.LOCALE我在 Struts 1.x 文档中找不到常量- 应该是吗org.apache.struts.Globals.LOCALE_KEY?或者其他LOCALE_KEY常数之一?


编辑: org.apache.struts.action.LOCALE是-的org.apache.struts.Global.LOCALE_KEY,因此用作键的值本身不应该成为问题。

验证 a 是否LOCALE已在Request. 我的理解是,如果LOCALE_KEY设置了,就PageContext.SESSION_SCOPE设置了。