Java Tutorial/Servlet/Internationlization I18N

Материал из Java эксперт
Версия от 05:06, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Japanese Hello World Servlet

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JapaneseHelloWorldServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
      ServletException {
    response.setContentType("text/html");
    response.setLocale(Locale.JAPANESE);
    PrintWriter out = response.getWriter();
    out.println("<FONT SIZE=+2>");
    out.println("\u4eca\u65e5\u306f\u4e16\u754c");
    out.println("</FONT>");
  }
}





Locale Information Servlet

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LocaleInformationServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
      ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    Locale userPreferredLocale = request.getLocale();
    Enumeration userPreferredLocales = request.getLocales();
    out.println("Preferred Locale: " + userPreferredLocale.toString());
    out.println("");
    out.print("Preferred Locales: ");
    while (userPreferredLocales.hasMoreElements()) {
      userPreferredLocale = (Locale) userPreferredLocales.nextElement();
      out.print(userPreferredLocale.toString() + ", ");
    }
    out.println();
    out.println("");
  }
}





Locale Session Servlet

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LocaleSessionServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
      ServletException {
    HttpSession userSession = request.getSession();
    if (userSession.isNew()) {
      userSession.setAttribute("userLocale", request.getLocale());
    }
  }
}





Servlet I18N: Page Header

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/plain; charset=Shift_JIS");
    PrintWriter out = res.getWriter();
    res.setHeader("Content-Language", "ja");
    Locale locale = new Locale("ja", "");
    DateFormat full = DateFormat.getDateTimeInstance(DateFormat.LONG,
                                                     DateFormat.LONG,
                                                     locale);
    out.println("In Japanese:");
    out.println("\u4eca\u65e5\u306f\u4e16\u754c");  // Hello World
    out.println(full.format(new Date()));
  }
}





Servlet I18N: Read From File

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/plain; charset=Shift_JIS");
    PrintWriter out = res.getWriter();
    res.setHeader("Content-Language", "ja");
    Locale locale = new Locale("ja", "");
    DateFormat full = DateFormat.getDateTimeInstance(DateFormat.LONG,
                                                     DateFormat.LONG,
                                                     locale);
    out.println("In Japanese:");
    try {
      FileInputStream fis =
        new FileInputStream(req.getRealPath("/HelloWorld.ISO-2022-JP"));
      InputStreamReader isr = new InputStreamReader(fis, "ISO-2022-JP");
      BufferedReader reader = new BufferedReader(isr);
      String line = null;
      while ((line = reader.readLine()) != null) {
        out.println(line);
      }
    }
    catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    out.println(full.format(new Date()));
  }
}





Servlet Spanish

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();
    res.setHeader("Content-Language", "es");
    Locale locale = new Locale("es", "");
    DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.LONG,
                                                    DateFormat.LONG,
                                                    locale);
    fmt.setTimeZone(TimeZone.getDefault());
    out.println("En Espa\u00f1ol:");
    out.println("\u00a1Hola Mundo!");
    out.println(fmt.format(new Date()));
  }
}





Servlet Unicode

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    Locale locale;
    DateFormat full;
    try {
      res.setContentType("text/plain; charset=UTF-8");
      //PrintWriter out = res.getWriter();
      PrintWriter out = new PrintWriter(
        new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);
      locale = new Locale("en", "US");
      full = DateFormat.getDateTimeInstance(DateFormat.LONG, 
                                            DateFormat.LONG,
                                            locale);
      out.println("In English appropriate for the US:");
      out.println("Hello World!");
      out.println(full.format(new Date()));
      out.println();
      locale = new Locale("es", "");
      full = DateFormat.getDateTimeInstance(DateFormat.LONG, 
                                            DateFormat.LONG,
                                            locale);
      out.println("En Espa\u00f1ol:");
      out.println("\u00a1Hola Mundo!");
      out.println(full.format(new Date()));
      out.println();
      locale = new Locale("ja", "");
      full = DateFormat.getDateTimeInstance(DateFormat.LONG,
                                            DateFormat.LONG,
                                            locale);
      out.println("In Japanese:");
      out.println("\u4eca\u65e5\u306f\u4e16\u754c");
      out.println(full.format(new Date()));
      out.println();
      locale = new Locale("zh", "");
      full = DateFormat.getDateTimeInstance(DateFormat.LONG,
                                            DateFormat.LONG,
                                            locale);
      out.println("In Chinese:");
      out.println("\u4f60\u597d\u4e16\u754c");
      out.println(full.format(new Date()));
      out.println();
      locale = new Locale("ko", "");
      full = DateFormat.getDateTimeInstance(DateFormat.LONG,
                                            DateFormat.LONG,
                                            locale);
      out.println("In Korean:");
      out.println("\uc548\ub155\ud558\uc138\uc694\uc138\uacc4");
      out.println(full.format(new Date()));
      out.println();
      locale = new Locale("ru", "");
      full = DateFormat.getDateTimeInstance(DateFormat.LONG,
                                            DateFormat.LONG,
                                            locale);
      out.println("In Russian (Cyrillic):");
      out.print("\u0417\u0434\u0440\u0430\u0432\u0441\u0442");
      out.println("\u0432\u0443\u0439, \u041c\u0438\u0440");
      out.println(full.format(new Date()));
      out.println();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}





Servlet Unicode Escape String

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    try {
      res.setContentType("text/plain; charset=UTF-8");
      PrintWriter out = res.getWriter();
      String charset = req.getParameter("charset");
      String text = req.getParameter("text");
      BufferedReader reader = new BufferedReader(
        new InputStreamReader(new StringBufferInputStream(text), charset));
      text = reader.readLine();
      out.println("Received charset: " + charset);
      out.println("Received text: " + text);
      out.println("Received text (escaped): " + toUnicodeEscapeString(text));
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void doPost(HttpServletRequest req, HttpServletResponse res)
                                throws ServletException, IOException {
    doGet(req, res);
  }
  private static String toUnicodeEscapeString(String str) {
    // Modeled after the code in java.util.Properties.save()
    StringBuffer buf = new StringBuffer();
    int len = str.length();
    char ch;
    for (int i = 0; i < len; i++) {
      ch = str.charAt(i);
      switch (ch) {
        case "\\": buf.append("\\\\"); break;
        case "\t": buf.append("\\t"); break;
        case "\n": buf.append("\\n"); break;
        case "\r": buf.append("\\r"); break;
    
        default:
          if (ch >= " " && ch <= 127) {
            buf.append(ch);
          }
          else {
            buf.append("\\");
            buf.append("u");
            buf.append(toHex((ch >> 12) & 0xF));
            buf.append(toHex((ch >>  8) & 0xF));
            buf.append(toHex((ch >>  4) & 0xF));
            buf.append(toHex((ch >>  0) & 0xF));
          }
      }
    }
    return buf.toString();
  }
  private static char toHex(int nibble) {
    return hexDigit[(nibble & 0xF)];
  }
  private static char[] hexDigit = {
    "0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"
  };
}





Servlet UTF8 Page

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
  PrintWriter out = null;
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {
    try {
      // Get a reader to read the incoming data
      BufferedReader reader = req.getReader();
      // Get a writer to write the data in UTF-8
      res.setContentType("text/html; charset=UTF-8");
      //PrintWriter out = res.getWriter();
      out = new PrintWriter(
        new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);
      char[] buf = new char[4 * 1024];  // 4Kchar buffer
      int len;
      while ((len = reader.read(buf, 0, buf.length)) != -1) {
        out.write(buf, 0, len);
      }
      out.flush();
    }
    catch (Exception e) {
      out.println("Problem filtering page to UTF-8");
      getServletContext().log(e, "Problem filtering page to UTF-8");
    }
    out.println("Done");
  }
  public void doPost(HttpServletRequest req, HttpServletResponse res)
                         throws ServletException, IOException {
    doGet(req, res);
  }
}





Set content type to charset=ISO-/td>

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UnknownEncodingServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
      ServletException {
    response.setContentType("text/html; charset=ISO-8850-1");
    PrintWriter out = response.getWriter();
  }
}