만약 Spring을 사용하고 있다면 아래와 같이 Spring 자체 기능으로 쉽게 메시지를 관리를 할 수 있습니다.

<spring:message code="sarc.io.name" />

하지만 Spring 등 Framework이 적용되지 않은 프로젝트의 경우는 자바 자체의 기능으로 메시지 관리를 구현할 수 밖에 없다. 그리고 그 해결책은 java.util.ResourceBundle이다.

거두절미하고 다음과 같은 메소드를 만들어 사용할 수 있다.

public static String getMessage(String bundle, String key) {
        String value = null;
        ResourceBundle rb = null;
 
        try {
                rb = ResourceBundle.getBundle(bundle);
                value = rb.getString(key);
        } catch(Exception e) {
                e.printStackTrace();
        }
        return value;
}

위에서 만들어 본 getMessage 메소드는 key-value로 이루어진 properties 파일 위치와 그 내부의 key를 통해 최종 value를 리턴하고 있다. 예를 들어 WEB-INF/classes/web/messages 하위의 menu.properties 파일에 있는 sarc.io.name에 대한 value를 얻고자 한다면 getMessage("web.messages.menu","sarc.io.name") 과 같이 사용하면 된다.

ResourceBundle은 locale-specific이므로 locale에 따라 메시지를 다르게 표현할 수 있다. 만약 한국어 메시지를 분리하고자 한다면 menu.properties와 함께 menu_ko.properties를 생성한다. 물론 메시지 파일 접근시에 굳이 "_ko"라는 postfix를 언급할 필요는 없다. 자동이다.

UTF-8 환경에서 ResourceBundle을 통해 한글 String을 얻어 JSP에서 사용할 때 한글이 깨진다면, 다음과 같이 처리한다.  

value = new String(rb.getString(key).getBytes("8859_1"),"UTF-8");