국제화 컨텍스트 API 사용

엔터프라이즈 JavaBeans(EJB) 클라이언트 애플리케이션, 서블릿, 엔터프라이즈 Bean은 국제화 컨텍스트 API를 사용하여 국제화 컨텍스트를 프로그래밍 방식으로 확보 및 관리할 수 있습니다. 웹 서비스 클라이언트 애플리케이션에 대해 API를 사용하여 EJB 클라이언트와 동일한 방식으로 국제화 컨텍스트를 확보하고 관리합니다.

시작하기 전에

java.util and com.ibm.websphere.i18n.context 패키지에는 EJB 애플리케이션 내에서 국제화 서비스를 사용하는 데 필요한 모든 클래스가 포함됩니다.

프로시저

  1. 국제화 컨텍스트 API에 대한 액세스를 확보하십시오.

    해당 컴포넌트의 국제화 메소드 내(예: 서블릿의 init 메소드 내 또는 엔터프라이즈 Bean의 SetXxxContext 메소드) 애플리케이션 컴포넌트의 라이프사이클에 한 번 국제화 컨텍스트 API 참조를 분석합니다. 웹 서비스 클라이언트 프로그램의 경우, 초기화 중 국제화 컨텍스트 API에 대한 참조를 분석합니다. 웹 서비스에 사용 가능한 stateless 세션 Bean의 경우, setSessionContext 메소드에서 참조를 분석합니다.

  2. 호출자 로케일 및 시간대에 액세스하십시오.

    애플리케이션 컴포넌트의 모든 원격 호출에는 해당 호출을 실행하고 있는 스레드와 연관된 호출자 국제화 컨텍스트가 있습니다. 호출자 컨텍스트는 국제화 서비스와 미들웨어에서 EJB(Enterprise JavaBeans) 비즈니스 메소드나 서블릿 서비스 메소드와 같은 요청 대상으로 전파됩니다. 이 태스크는 웹 서비스 클라이언트 프로그램에도 적용됩니다.

  3. 호출 로케일 및 시간대에 액세스하십시오.

    서블릿 서비스 또는 EJB(Enterprise JavaBeans) 비즈니스 메소드의 모든 원격 호출에는 해당 호출을 실행 중인 스레드와 연관된 호출 국제화 컨텍스트가 있습니다. 호출 컨텍스트는 서블릿과 비즈니스 메소드 구현이 실행하는 국제화 컨텍스트입니다. 국제화 서비스와 미들웨어에 의해 다음 호출에서 전파됩니다. 이 태스크는 웹 서비스 클라이언트 프로그램에도 적용됩니다.

결과

결과 컴포넌트는 애플리케이션 관리 국제화(AMI)를 사용하도록 지시됩니다. AMI에 대한 자세한 정보는 국제화 컨텍스트: 관리 정책의 내용을 참조하십시오.

지원되는 각 애플리케이션은 국제화 컨텍스트 API를 다르게 사용합니다. 각 컴포넌트 유형에서 API를 사용하는 방법을 설명하는 코드 예가 제공됩니다. API 사용법의 차이점과 다른 코딩 팁도 관련 명령문 블록 앞의 주석에 표기됩니다.

EJB 클라이언트 프로그램에서 국제화 컨텍스트 관리: 다음 코드 예는 포함된 EJB 클라이언트 프로그램이나 웹 서비스 클라이언트 프로그램에서 국제화 컨텍스트 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

서블릿에서 국제화 컨텍스트 관리: 다음 코드 예는 서블릿 내에서 국제화 컨텍스트 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 또는 웹 서비스 사용 세션 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 헤더에 국제화 컨텍스트 표시: 이 코드 예는 웹 서비스 요청의 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