使用国际化上下文 API

Enterprise JavaBeans (EJB) 客户机应用程序、servlet 和企业 Bean 可以使用国际化上下文 API 以编程方式获取和管理国际化上下文。对于 Web Service 客户机应用程序,您可以通过 EJB 客户机的相同方式使用此 API 获取和管理国际化上下文。

开始之前

java.util and com.ibm.websphere.i18n.context 包中包含使用 EJB 应用程序中的国际化服务所需的所有类。

过程

  1. 获取对国际化上下文 API 的访问权

    在应用程序组件的生命周期中,在该组件的初始化方法中(例如,在 servlet 的 init 方法中或企业 Bean 的 SetXxxContext 方法中)对国际化上下文 API 引用进行一次性解析。对于 Web Service 客户机程序,在初始化过程中对国际化上下文 API 的引用进行解析。对于支持 Web Service 的无状态会话 Bean,在 setSessionContext 方法中对引用进行解析。

  2. 访问调用者语言环境和时区

    应用程序组件的每个远程调用都有一个关联的调用者国际化上下文与运行该调用的线程关联在一起。国际化服务和中间件将调用者上下文传播到请求的目标,如 Enterprise JavaBeans (EJB) 业务方法或 servlet 服务方法。此任务还适用于 Web Service 客户机程序。

  3. 访问调用语言环境和时区

    servlet 服务或 Enterprise JavaBeans (EJB) 业务方法的每个远程调用都有一个与运行该调用的线程关联的调用国际化上下文。调用上下文是 servlet 和业务方法实现运行所在的国际化上下文;国际化服务和中间件将在后续调用中传播它。此任务还适用于 Web Service 客户机程序。

结果

生成的组件将使用应用程序管理的国际化 (AMI)。有关 AMI 的更多信息,请参阅国际化上下文:管理策略

示例

每个受支持的应用程序组件对国际化上下文 API 的使用各有不同。提供一些代码示例,用来说明如何在各个组件类型中使用 API。将在相应语句段之前的注释中列出 API 用法的不同之处和其他编码技巧。

管理 EJB 客户机程序中的国际化上下文:以下代码示例说明了如何在包含的 EJB 客户机程序或 Web Service 客户机程序中使用国际化上下文 API。

//------------------------------------------
// Basic Example: J2EE EJB client.
//------------------------------------------
package examples.basic;

//------------------------------------------
// INTERNATIONALIZATION SERVICE: Imports.
//------------------------------------------
import com.ibm.websphere.i18n.context.UserInternationalization;
import com.ibm.websphere.i18n.context.Internationalization;
import com.ibm.websphere.i18n.context.InvocationInternationalization;

import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import java.util.Locale;
import java.util.SimpleTimeZone;

public class EjbClient {

  public static void main(String args[]) {

    //--------------------------------------------------
    // INTERNATIONALIZATION SERVICE: API references.
    //--------------------------------------------------
    UserInternationalization userI18n = null;
    Internationalization callerI18n = null;
    InvocationInternationalization invocationI18n = null;
   
    //--------------------------------------------------
    // INTERNATIONALIZATION SERVICE: JNDI name. 
    //--------------------------------------------------
    final String UserI18NUrl =
        "java:comp/websphere/UserInternationalization";

    //--------------------------------------------------
    // INTERNATIONALIZATION SERVICE: Resolve the API.
    //--------------------------------------------------
    try {
     Context initialContext = new InitialContext();    
     userI18n = (UserInternationalization)initialContext.lookup(
         UserI18NUrl);
     callerI18n = userI18n.getCallerInternationalization();
     invI18n = userI18n.getInvocationInternationalization ();
    } catch (NamingException ne) {
      log("Error: Cannot resolve UserInternationalization: Exception: " + ne);
    } catch (IllegalStateException ise) {
      log("Error: UserInternationalization is not available: " + ise);
    }
    ...

    //--------------------------------------------------------------------
    // INTERNATIONALIZATION SERVICE: Set invocation context.
    //
    // Under Application-managed Internationalization (AMI), contained EJB 
    // client programs may set invocation context elements. The following 
    // statements associate the supplied invocation locale and time zone 
    // with the current thread. Subsequent remote bean method calls will 
    // propagate these context elements.
    //--------------------------------------------------------------------
    try {
      invocationI18n.setLocale(new Locale("fr", "FR", ""));
      invocationI18n.setTimeZone("ECT");
    } catch (IllegalStateException ise) {
      log("An anomaly occurred accessing Invocation context: " + ise );
    }
    ...

    //--------------------------------------------------------------------
    // INTERNATIONALIZATION SERVICE: Get locale and time zone.
    //
    // Under AMI, contained EJB client programs can get caller and
    // invocation context elements associated with the current thread. 
    // The next four statements return the invocation locale and time zone 
    // associated above, and the caller locale and time zone associated 
    // internally by the service. Getting a caller context element within 
    // a contained client results in the default element of the JVM.
    //--------------------------------------------------------------------
    Locale invocationLocale = null;
    SimpleTimeZone invocationTimeZone = null;
    Locale callerLocale = null;
    SimpleTimeZone callerTimeZone = null;
    try {
      invocationLocale = invocationI18n.getLocale();
      invocationTimeZone =                           
          (SimpleTimeZone)invocationI18n.getTimeZone();
      callerLocale = callerI18n.getLocale();
      callerTimeZone = SimpleTimeZone)callerI18n.getTimeZone();
    } catch (IllegalStateException ise) {
      log("An anomaly occurred accessing I18n context: " + ise );
    }

    ...
  } // main

  ...
  void log(String s) {
    System.out.println (((s == null) ? "null" : s));
  }
} // EjbClient

管理 Servlet 中的国际化上下文:以下代码示例说明了如何使用 servlet 中的国际化上下文 API。注意 init 方法和 doPost 方法中的注释。

...
//--------------------------------------------------------------------
// INTERNATIONALIZATION SERVICE: Imports.
//--------------------------------------------------------------------
import com.ibm.websphere.i18n.context.UserInternationalization;
import com.ibm.websphere.i18n.context.Internationalization;
import com.ibm.websphere.i18n.context.InvocationInternationalization;

import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import java.util.Locale;

public class J2eeServlet extends HttpServlet {

  ...
  //------------------------------------------------------------------
  // INTERNATIONALIZATION SERVICE: API references.
  //------------------------------------------------------------------
  protected UserInternationalization userI18n = null;
  protected Internationalization i18n = null;
  protected InvocationInternationalization invI18n = null;

  //------------------------------------------------------------
  // INTERNATIONALIZATION SERVICE: JNDI name. 
  //------------------------------------------------------------
  public static final String UserI18NUrl = 
      "java:comp/websphere/UserInternationalization";  

  protected Locale callerLocale = null;
  protected Locale invocationLocale = null;

  /**
   * Initialize this servlet.
   * Resolve references to the JNDI initial context and the
   * internationalization context API.
   */
  public void init() throws ServletException {

    //------------------------------------------------------------------
    // INTERNATIONALIZATION SERVICE: Resolve API.
    //
    // Under Container-managed Internationalization (CMI), servlets have 
    // read-only access to invocation context elements. Attempts to set these 
    // elements result in an IllegalStateException.
    //
    // Suggestion: cache all internationalization context API references 
    // once, during initialization, and use them throughout the servlet 
    // lifecycle.
    //------------------------------------------------------------------
    try {
      Context initialContext = new InitialContext();
      userI18n = (UserInternationalization)initialContext.lookup(UserI18nUrl);
      callerI18n = userI18n.getCallerInternationalization();
      invI18n = userI18n.getInvocationInternationalization();
    } catch (NamingException ne) {
      throw new ServletException("Cannot resolve UserInternationalization" + ne);
    } catch (IllegalStateException ise) {
      throw new ServletException ("Error: UserInternationalization is not
         available: " + ise);
    }
    ...
  } // init
  
  /**
   * Process incoming HTTP GET requests.
   * @param request Object that encapsulates the request to the servlet
   * @param response Object that encapsulates the response from the
   *    Servlet.
   */
  public void doGet(
      HttpServletRequest  request, 
      HttpServletResponse response)
    throws ServletException, IOException {
    doPost(request, response);
  } // doGet

  /**
   * Process incoming HTTP POST requests
   * @param request Object that encapsulates the request to 
   *    the Servlet.
   * @param response Object that encapsulates the response from
   *    the Servlet.
   */
  public void doPost(
      HttpServletRequest  request,
      HttpServletResponse response)
    throws ServletException, IOException {

    ...
    //--------------------------------------------------------------------
    // INTERNATIONALIZATION SERVICE: Get caller context.
    //
    // The internationalization service extracts the accept-languages
    // propagated in the HTTP request and associates them with the 
    // current thread as a list of locales within the caller context.
    // These locales are accessible within HTTP Servlet service methods 
    // using the caller internationalization object.
    // 
    // If the incoming HTTP request does not contain accept languages,
    // the service associates the server's default locale. The service
    // always associates the GMT time zone.
    //
    //--------------------------------------------------------------------
    try {
      callerLocale = callerI18n.getLocale();   // caller locale
      // the following code enables you to get invocation locale,
      // which depends on the Internationalization policies.
      invocationLocale = invI18n.getLocale();  // invocation locale
    } catch (IllegalStateException ise) {
      log("An anomaly occurred accessing Invocation context: " + ise);
    }
    // NOTE: Browsers may propagate accept-languages that contain a 
    // language code, but lack a country code, like "fr" to indicate 
    // "French as spoken in France."  The following code supplies a
    // default country code in such cases.
    if (callerLocale.getCountry().equals(""))
      callerLocale = AccInfoJBean.getCompleteLocale(callerLocale);
    
    // Use iLocale in JDK locale-sensitive operations, etc.
    ...
  } // doPost
  
  ...
  void log(String s) {
    System.out.println (((s == null) ? "null" : s));
  }
} // CLASS J2eeServlet

管理会话 Bean 中的国际化上下文:此代码示例说明了如何使用国际化服务在会话 Bean 或支持 Web Service 的会话 Bean 中执行已本地化的操作。

...   
//------------------------------------------------------------
// INTERNATIONALIZATION SERVICE: Imports.
//------------------------------------------------------------
import com.ibm.websphere.i18n.context.UserInternationalization;
import com.ibm.websphere.i18n.context.Internationalization;
import com.ibm.websphere.i18n.context.InvocationInternationalization;

import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.NamingException;
import java.util.Locale;

/**
 * This is a stateless Session Bean Class
 */
public class J2EESessionBean implements SessionBean {

  //------------------------------------------------------------
  // INTERNATIONALIZATION SERVICE: API references.
  //------------------------------------------------------------
  protected UserInternationalization        userI18n = null;
  protected InvocationInternationalization  invI18n  = null;

  //------------------------------------------------------------
  // INTERNATIONALIZATION SERVICE: JNDI name. 
  //------------------------------------------------------------
  public static final String UserI18NUrl = 
      "java:comp/websphere/UserInternationalization";  
  ...
  
  /**
   * Obtain the appropriate internationalization interface 
   * reference in this method.
   * @param ctx javax.ejb.SessionContext
   */
  public void setSessionContext(javax.ejb.SessionContext ctx) {

    //------------------------------------------------------------
    // INTERNATIONALIZATION SERVICE: Resolve the API.
    //------------------------------------------------------------
    try {
      Context initialContext = new InitialContext();    
      userI18n = (UserInternationalization)initialContext.lookup(
          UserI18NUrl);
      invI18n = userI18n.getInvocationInternationalization();
    } catch (NamingException ne) {
      log("Error: Cannot resolve UserInternationalization: Exception: " + ne);
        
    } catch (IllegalStateException ise) {
      log("Error: UserInternationalization is not available: " + ise);
    }
  } // setSessionContext 

 /**
  * Set up resource bundle using I18n Service
  */
  public void setResourceBundle()
  {
    Locale invLocale   = null;

    //------------------------------------------------------------
    // INTERNATIONALIZATION SERVICE: Get invocation context.
    //------------------------------------------------------------
    try {
      invLocale = invI18n.getLocale();
    } catch (IllegalStateException ise) {
      log ("An anomaly occurred while accessing Invocation context: " + ise );
    }
    try {    
      Resources.setResourceBundle(invLocale);
      // Class Resources provides support for retrieving messages from
      // the resource bundle(s). See Currency Exchange sample source code.
    } catch (Exception e) {
      log("Error: Exception occurred while setting resource bundle: " + e);
    }
  } // setResourceBundle

  /**
   * Pass message keys to get the localized texts
   * @return java.lang.String []
   * @param key java.lang.String []
   */
  public String[] getMsgs(String[] key) {
    setResourceBundle();
    return Resources.getMsgs(key);    
  }

  ...
  void log(String s) {
    System.out.println(((s == null) ? ";null" : s));
  }
} // CLASS J2EESessionBean

表示 SOAP 头中的国际化上下文:此代码示例说明了如何在 Web Service 请求的 SOAP 头中表示国际化上下文。

<InternationalizationContext>
   <Locales>
      <Locale>
         <LanguageCode>ja</LanguageCode>
         <CountryCode>JP</CountryCode>
         <VariantCode>Nihonbushi</VariantCode>
      </Locale>
      <Locale>
         <LanguageCode>fr</LanguageCode>
         <CountryCode>FR</CountryCode>
      </Locale>
      <Locale>
         <LanguageCode>en</LanguageCode>
         <CountryCode>US</CountryCode>
      </Locale>
   </Locales>
   <TimeZoneID>JST</TimeZoneID>
</InternationalizationContext>
对照以下模式,此表示有效:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:element name="InternationalizationContext" 
                 type="InternationalizationContextType"> 
    </xsd:element>

    <xsd:complexType name="InternationalizationContextType">
        <xsd:sequence> 
            <xsd:element name="Locales" 
                         type="LocalesType">
            </xsd:element>
            <xsd:element name="TimeZoneID" 
                         type="xsd:string">
            </xsd:element>
        </xsd:sequence> 
    </xsd:complexType>

    <xsd:complexType name="LocalesType">
        <xsd:sequence> 
            <xsd:element name="Locale" 
                         type="LocaleType" 
                         minOccurs="0" 
                         maxOccurs="unbounded"> 
            </xsd:element>
        </xsd:sequence> 
    </xsd:complexType>

    <xsd:complexType name="LocaleType"> 
        <xsd:sequence> 
            <xsd:element name="LanguageCode" 
                         type="xsd:string" 
                         minOccurs="0" 
                         maxOccurs="1"> 
            </xsd:element> 
            <xsd:element name="CountryCode" 
                         type="xsd:string" 
                         minOccurs="0" 
                         maxOccurs="1"> 
            </xsd:element>
            <xsd:element name="VariantCode" 
                         type="xsd:string" 
                         minOccurs="0" 
                         maxOccurs="1"> 
            </xsd:element>
         </xsd:sequence>
    </xsd:complexType>
    
</xsd:schema>

指示主题类型的图标 任务主题



时间戳记图标 最近一次更新时间: last_date
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=cord&product=was-nd-mp&topic=tin_manageapi
文件名:tin_manageapi.html