Servlet internationalization


Before we begin, let’s look at three important terms:

  • Internationalization (i18n): This means A website provides different versions of content translated into the language or nationality of its visitors.

  • Localization (l10n): This means adding resources to a website to adapt it to a specific geographical or cultural region, such as translating the website into Hindi (Hindi).

  • Locale: This is a special cultural or geographical area. It usually refers to the language symbol followed by an underscore and a country symbol. For example "en_US" represents the English locale for US.

There are some considerations when building a global website. This tutorial won't go into the full details of these considerations, but it will give you a good example of how to use differential targeting (i.e. locale settings) to render a page in different languages.

The Servlet can pick up the appropriate version of the website based on the requester's locale and provide the appropriate version of the website based on the local language, culture, and needs. The following are methods in the request object that return Locale objects.

java.util.Locale request.getLocale()

Detecting Locale

Listed below are the important locale methods that you can use to detect the geolocation, language, and locale of the requester. All methods below display the country name and language name set in the requester's browser.

##123456

Example

This example demonstrates how to display the language and related country of a request:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Locale;

public class GetLocale extends HttpServlet{
    
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // 获取客户端的区域设置
      Locale locale = request.getLocale();
      String language = locale.getLanguage();
      String country = locale.getCountry();

      // 设置响应内容类型
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      String title = "检测区域设置";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
        "<html>\n" +
        "<head><title>" + title + "</title></head>\n" +
        "<body bgcolor=\"#f0f0f0\">\n" +
        "<h1 align=\"center\">" + language + "</h1>\n" +
        "<h2 align=\"center\">" + country + "</h2>\n" +
        "</body></html>");
  }
}

Language settings

Servlet can output in Western European languages ​​(such as English , Spanish, German, French, Italian, Dutch, etc.). Here, in order to display all characters correctly, it is very important to set the Content-Language header.

The second point is to use HTML entities to display all special characters, for example, "ñ" means "ñ", "¡" means "¡", as shown below:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Locale;

public class DisplaySpanish extends HttpServlet{
    
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
    // 设置响应内容类型
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    // 设置西班牙语言代码
    response.setHeader("Content-Language", "es");

    String title = "En Espa&ntilde;ol";
    String docType =
     "<!doctype html public \"-//w3c//dtd html 4.0 " +
     "transitional//en\">\n";
     out.println(docType +
     "<html>\n" +
     "<head><title>" + title + "</title></head>\n" +
     "<body bgcolor=\"#f0f0f0\">\n" +
     "<h1>" + "En Espa&ntilde;ol:" + "</h1>\n" +
     "<h1>" + "&iexcl;Hola Mundo!" + "</h1>\n" +
     "</body></html>");
  }
}

Locale-specific dates

You can use the java.text.DateFormat class and its static method getDateTimeInstance() to format locale-specific dates and times. The following example demonstrates how to format a date specific to a given locale:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Locale;
import java.text.DateFormat;
import java.util.Date;

public class DateLocale extends HttpServlet{
    
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
    // 设置响应内容类型
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    // 获取客户端的区域设置
    Locale locale = request.getLocale( );
    String date = DateFormat.getDateTimeInstance(
                                  DateFormat.FULL, 
                                  DateFormat.SHORT, 
                                  locale).format(new Date( ));

    String title = "特定于区域设置的日期";
    String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
      "<html>\n" +
      "<head><title>" + title + "</title></head>\n" +
      "<body bgcolor=\"#f0f0f0\">\n" +
      "<h1 align=\"center\">" + date + "</h1>\n" +
      "</body></html>");
  }
}

Locale-specific currency

You can use the java.text.NumberFormat class and its Static method getCurrencyInstance() to format a number (such as a long or a double) into a locale-specific currency. The following example demonstrates how to format currency specific to a given locale:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Locale;
import java.text.NumberFormat;
import java.util.Date;

public class CurrencyLocale extends HttpServlet{
    
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
    // 设置响应内容类型
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    // 获取客户端的区域设置
    Locale locale = request.getLocale( );
    NumberFormat nft = NumberFormat.getCurrencyInstance(locale);
    String formattedCurr = nft.format(1000000);

    String title = "特定于区域设置的货币";
    String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
      "<html>\n" +
      "<head><title>" + title + "</title></head>\n" +
      "<body bgcolor=\"#f0f0f0\">\n" +
      "<h1 align=\"center\">" + formattedCurr + "</h1>\n" +
      "</body></html>");
  }
}

Locale-specific percentage

You can use the java.text.NumberFormat class and its Static method getPercentInstance() to format locale-specific percentages. The following example demonstrates how to format a percentage specific to a given locale:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Locale;
import java.text.NumberFormat;
import java.util.Date;

public class PercentageLocale extends HttpServlet{
    
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
    // 设置响应内容类型
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    // 获取客户端的区域设置
    Locale locale = request.getLocale( );
    NumberFormat nft = NumberFormat.getPercentInstance(locale);
    String formattedPerc = nft.format(0.51);

    String title = "特定于区域设置的百分比";
    String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
      "<html>\n" +
      "<head><title>" + title + "</title></head>\n" +
      "<body bgcolor=\"#f0f0f0\">\n" +
      "<h1 align=\"center\">" + formattedPerc + "</h1>\n" +
      "</body></html>");
  }
}
Serial numberMethod & Description
String getCountry( )This method returns the country code for this locale in ISO 3166 format with 2 uppercase letters.
String getDisplayCountry()This method returns the name of the country appropriate for the locale displayed to the user.
String getLanguage()This method returns the language code for this locale in lowercase ISO 639 format.
String getDisplayLanguage()This method returns the name of the language appropriate for the locale displayed to the user.
String getISO3Country()This method returns the three-letter abbreviation of the country for this locale.
String getISO3Language()This method returns the three-letter abbreviation of the language for this locale.