Java/Common
Java(JSP/Servlet)에서 다국어(i18n) 사용하기
조영래
2020. 4. 3. 13:50
Spring 에서는 다국어를 지원(국제화) 할 수 있는 서버스가 존재 한다. 하지만 항상 Spring만을 사용할 수 없기에 일반 JSP/Servlet 에서 다국어를 사용할 수 있게 해보자
1. ResourceBundle 객체를 국가_언어 별로 생성한다
2. 필요에 따라 특정 국가_언어 ResourceBundle 객체를 이용하여 메세지를 가져온다
package com.ariulsoft.izen.homepage.i18n;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
public class I18N {
private Map<String, ResourceBundle> bundlemap;
public I18N() {
//default locale
//ResourceBundle bundle = ResourceBundle.getBundle("ApplicationMessages");
//Get ResourceBundle with Locale that are already defined
ResourceBundle bundleKo = ResourceBundle.getBundle("ApplicationMessages", Locale.KOREA);
//Get resource bundle when Locale needs to be created
ResourceBundle bundleSVSE = ResourceBundle.getBundle("ApplicationMessages", new Locale("en", "EU"));
bundlemap = new HashMap<String, ResourceBundle>();
bundlemap.put(Locale.KOREA.toString(), bundleKo);
bundlemap.put(Locale.US.toString(), bundleSVSE);
}
/**
* 기본 US 프로퍼티에서 key의 value 가져오기
* @param key
* @return
*/
public String getString(String key) {
String returnVaule = "";
ResourceBundle bundle = bundlemap.get(Locale.US.toString());
if(key != null) {
returnVaule = bundle.getString(key);
if(returnVaule == null) {
returnVaule = "";
}
}
return returnVaule;
}
/**
* 국가_언어 프로퍼티에서 key의 value 가져오기
* @param rsKey
* @param key
* @return
*/
public String getString(String rsKey, String key) {
String returnValue = "";
if(rsKey != null && key != null) {
ResourceBundle bundle = bundlemap.get(rsKey);
if(bundle != null) {
try {
returnValue = bundle.getString(key);
if(returnValue == null) {
returnValue = "";
}
}
catch(Exception e) {
e.printStackTrace();
returnValue = "";
}
}
else {
returnValue = getString(key);
}
}
return returnValue;
}
}
<!-- test.jsp -->
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ page import="java.util.Locale" %>
<%@ page import="com.ariulsoft.izen.homepage.i18n.I18N" %>
<%
Locale locale = request.getLocale();
I18N i18nObject = new I18N();
String test = i18nObject.getString(locale.toString(), "test");
%>