본문 바로가기
Programming/Spring

[spring] 다국어 지원

by NAMP 2016. 4. 22.

[spring] 다국어 지원

다국어 지원을 위해서 메세지 리소스를 구축해야 함
resources 폴더에 작업

다국어 지원 개념

메시지 소스 파일

resources 에 패키지 생성

resources

messages 패키지 생성

messages 패키지 생성

message_ko.properties 파일 생성

내용입력

hello=안녕하세요
login.success=로그인 되었습니다. {0}님
login.fail=id:{0} 로그인 실패

영어 기반 파일 생성. message_en.properties 파일 생성

hello=HI!!
login.success=Welcome {0}
login.fail=id:{0} retry

message 로 시작하는 프로퍼티 파일을 만들었다.
시스템의 로케일에 따라 언어별 코드가 매핑되어 리소스 파일을 사용한다.

applicationContext 수정

org.springframework.context.support.ResourceBundleMessageSource 클래스 사용

bean 추가

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" ></bean>

MessageSource 정의

메시지 파일의 경로를 알려줘야 한다.
setter 인젝션 사용

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" >
    <property name="basenames">
        <value>messages.message</value>
    </property>
</bean>

[패키지].[파일명] 의 포맷

ApplicationContext 주소를 얻는다.

    public static void main(String[] args) {
        String[] config = {"applicationContext.xml"};
        ApplicationContext context = new ClassPathXmlApplicationContext(config);        
    }

여기에서 벌어지는 일은 다음과 같다.

applicationContext.xml 에서

  1. 컴포넌트 스캔
  2. @Component 들을 띄운다.
  3. @Service 띄운다.
  4. @Resource 를 삽입한다.
  5. messageSource 객체 생성

현재 로케일에 따라 값을 반환한다.

context.getMessage(“hello”)

ApplicationContext 에서 메시지를 관리하고 있다.

    public static void main(String[] args) {
        String[] config = {"applicationContext.xml"};
        ApplicationContext context = new ClassPathXmlApplicationContext(config);
        
        String msg = context.getMessage("hello", null, Locale.KOREA);
        System.out.println(msg);
    }

출력

안녕하세요

메시지에 변수 바인딩

String msg = context.getMessage("hello", null, Locale.KOREA);
System.out.println(msg);
    
String msg2 = context.getMessage("login.success", new Object[]{"MyID"}, Locale.ENGLISH);
System.out.println(msg2);

출력

안녕하세요
Welcome MyID

메시지는 context 가 관리

login 이 실패하는 경우를 처리해 보자.

System.out.println(service.login("admin", "a1234"));
System.out.println(service.login("admin", "1234"));

ServletContext 정보가 필요한 경우가 많다.
getServletContext 를 하면 반환된다.

POJO 기반이기에 강제성이 없다. 필요하면 인터페이스를 찾아서 사용한다.

ApplicationContextAware 를 구현하고 있다면 setApplicationContext() 메소드를 호출한다.
ApplicationContext 주소만 알면 사용할 수 있다.

ApplicationContext context;

로그인 실패인 경우 처리 코드 추가

@Override
public UserVO login(String id, String pw) {
    UserVO vo = dao.login(id, pw);
    String msg = "";
    if (vo != null){
        msg = context.getMessage("login.success", new String[]{id}, Locale.KOREA); 
    }else{
        msg = context.getMessage("login.fail", new String[]{id}, Locale.KOREA);
    }
    System.out.println(msg);
    return vo;
}

Exception in thread "main" java.lang.NullPointerException 을 처리해야 한다.

인터페이스 추가

public class UserServiceImpl implements UserService, ApplicationContextAware {...}

자동 호출되는 메소드

    @Override
    public void setApplicationContext(ApplicationContext context)
            throws BeansException {
        this.context = context;        
    }

출력 결과

로그인 되었습니다. admin님
UserVO [userid=admin, username=관리자, userpwd=a1234, email=admin@mc.co.kr, phone=02-1234, address=서울 역삼]
UserDAO_JDBC
id:admin 로그인 실패
null

스프링이 관리하는 객체들은 강제성이 없다.
핸들링을 하다보면 특정 기능을 사용해야 하는 경우가 있다.
제공하고 있는 인터페이스를 사용한다.

@Autowired어노테이션 사용도 가능하다

@Autowired
ApplicationContext context;

동일한 결과를 얻을 수 있다.

'Programming > Spring' 카테고리의 다른 글

[Spring] JDBC 설정  (0) 2016.04.24
[spring] 데이터 접근 디자인 패턴  (0) 2016.04.23
[spring] Annotation 기반 AOP 설정  (0) 2016.04.22
[spring] XML 기반 AOP 설정  (0) 2016.04.21
[spring] AOP (Aspect Oriented Programming)  (0) 2016.04.21

댓글