Recent Posts
Recent Comments
Link
06-28 05:11
Today
Total
관리 메뉴

삶 가운데 남긴 기록 AACII.TISTORY.COM

Spring MVC 다국어 처리 본문

DEV&OPS/Java

Spring MVC 다국어 처리

ALEPH.GEM 2023. 1. 18. 22:18

여기서는 한국어와 영어만을 대상으로 합니다.

 

properties 파일 작성

Spring MVC 프로젝트에서... src/main/resources 경로에 message_ko.properties 와 message_en.properties 파일을 생성합니다.

그러면 빌드와 배포를 했을 때 WEB-INF/classes 경로(classpath)에 프로퍼티 파일들이 생성됩니다.

이 프로퍼티 파일들은 유니코드로 저장되며, 이클립스를 전자정부프레임워크를 사용하거나 properties editor 플러그인을 사용하면 자동으로 유니코드를 한국어로 표기해줍니다.

Help > Install New Software... > Add...

Name : properties editor

Location : http://propedit.sourceforge.jp/eclipse/updates

 

message_ko.properties 예) 

####################################################################
STAT.STAT=예약 상태
STAT.STAT01=예약 신청
STAT.STAT02=예약 취소
STAT.STAT03=예약 완료
STAT.STAT04=예약 실패

message_en.properties 예) 

STAT.STAT=Reservation status
STAT.STAT01=Reservation Application
STAT.STAT02=Cancel Reservation
STAT.STAT03=Reservation Complete
STAT.STAT04=Reservation Failure

 

 

스프링 설정

여기서는 root-context.xml에 bean을 등록 합니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 생략 -->

	<!-- MessageSource Configuration : 메시지 프로퍼티 파일 bean id 변경 금지. 60초마다 프로퍼티 파일을 갱신해서 서버 재시작이 필요 없음 -->
	<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basenames">
			<list>
				<value>classpath:/message</value>
			</list>
		</property>
		<property name="cacheSeconds">
			<value>60</value>
		</property>
		<property name="defaultEncoding" value="UTF-8"/>
	</bean>
	<!-- LocaleResolver Registration : 세션값으로 로케일(언어)을 관리 bean id 변경 금지 -->
	<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
		<property name="defaultLocale" value="ko" />
	</bean>
    
 <!-- 생략 -->

주의할 점은 실제 프로퍼티 파일이 message_ko.properites, message_en.properties 이더라도

basename 에 classpath:/message_ko 라고 적지말고 접두사 처럼 classpaht:/message까지만 적으면 프로퍼티 "파일이름_국가코드"는 스프링이 알아서 처리하게 되어있다는 것입니다.

패키지 경로(예:package)가 있다면 classpath:/package/message 처럼 적으면 됩니다.

그리고 bean id 는 지정된 것이라 바꾸면 안됩니다.

localeResolver는 세션을 이용하는 방법, 쿠키를 이용하는 방법, request header정보의 language값을 이용하는 방법이 있는데, 여기서는 Session을 이용하는 방법으로 구현해보겠습니다.

 

그리고 나서 인터셉터를 이용해서 locale 설정에 따라 메시지 출력(랜더링)을 제어해야 합니다.

이클립스 스프링MVC 프로젝트에서 src/main/webapp/WEB-INF/spring/servlet-context.xml 에 인터셉터를 등록합니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<!-- 생략 -->
	
	<!-- LocaleChangeInterceptor Registration : 인터셉터를 이용해 lang parameter 값으로  로케일(언어) 설정 -->
	<interceptors>
		<beans:bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
			<beans:property name="paramName" value="lang"/>
		</beans:bean>
	</interceptors>
	
</beans:beans>

역시 bean id는 변경해서는 안되며 파라메터 이름은 lang으로 지정했습니다.

그러면 request 요청시 파라메터에 ?lang=ko 혹은 ?lang=en 으로 요청하면 언어셋(Locale)을 그때 그때 변경 적용해서 유연하게 다국어 메시지 처리를 할 수 있게됩니다.

 

 

구현

서블릿에서 구현하는 방법

import java.util.Locale;
import org.springframework.context.MessageSource;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HomeController {
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	@Autowired
	SessionLocaleResolver localeResolver;

	@Autowired
	MessageSource messageSource;

	@RequestMapping(value = "/i18n.do", method = RequestMethod.GET)
	public String i18n(Locale locale, HttpServletRequest request, Model model) {

		// RequestMapingHandler로 부터 받은 Locale 객체
		logger.info("Welcome i18n! The client locale is {}.", locale);

		// localeResolver 로부터 Locale 을 출력
		logger.info("Session locale is {}.", localeResolver.resolveLocale(request));

		// JSP 페이지에서 EL식으로 사용할 수 있도록 모델에 등록합니다.
		model.addAttribute("siteCount", messageSource.getMessage("STAT.STAT", null, "default text", locale));

		return "i18n";
	}
}

messageSource 는

messageSource.getMessage("프로퍼티파일의키값", 대체값이 있는경우 값의배열, "메시지기본값", Locale);

처럼 사용할 수 있습니다.

 

jsp에서 <spring:message> 태그 라이브러리로 구현하는 방법

/WEB-INF/views/i18n.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
	<p>
		<a href="<c:url value="/i18n.do?lang=ko" />">한국어</a>
		<a href="<c:url value="/i18n.do?lang=en" />">English</a>
	</p>
	<p><spring:message code="STAT.STAT" text="default text" /></p>
	<p><spring:message code="STAT.STAT01" text="default text1" /></p>
</body>
</html>

이렇게 properties 파일에 등록한 키값에 해당하는 value 값이 출력되게 됩니다.

언어 셋을 바꾸려면 위 예제 처럼 URL?lang=en 처럼 parameter로 전달해서 바꿀 수 있습니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90

'DEV&OPS > Java' 카테고리의 다른 글

인텔리제이 세팅  (0) 2023.12.21
Spring MVC 프로젝트 구조  (0) 2023.01.19
Spring Web Project 한글 설정  (0) 2023.01.18
Spring MVC maven jdk11 tomcat9 mysql5 mybatis3 설정  (0) 2023.01.17
Spring AOP  (0) 2023.01.16