본문 바로가기
공부/Backend

Spring Boot

by 유스베리이 2024. 1. 6.

 

 메세지 리소스 파일 작성

 

메세지 리소스파일 

- 프로젝트에 지원가능한 각 언어에 대해 메시지 리소스 파일 (*.properties) 을 생성하여 출력할 메세지 작성

- key = value 쌍으로 구성 ( key 는 뷰 페이지에서 메세지를 참조하는데 사용)

- 기본 언어의 메세지 리소스 파일을 '파일 이름. properties' 형태로 작성

<messages.properties>
Person.form.Enter.message = 당신의 정보를 입력하세요

 

-다양한 언어로 된 뷰 페이지를 지원하려면 특정 언어별 리소스 파일 작성해야 함.

( 파일 이름_ 언어코드_국가코드.properties )

- 메세지 리소스 파일은 src/main.resources 폴더에 위치

파일형식 설명
파일이름.properties 시스템 언어/ 지역에 맞는 리소스 파일이 없을 때
파일이름_ko.properties 시스템 언어 코드가 한국어 일 때
파일이름_en.properties 시스템 언어 코드가 영어 일 때
파일이름_en_UK.properties 시스템 언어 코드가 영국 , 영어 일 때
파일이름_ja.properties 시스템 언어 코드가 일본어 일 때

 

12.2.2 MessageSource 환경 설정

MessageSource 인터페이스 : 웹 애플리케이션의 화면에 한글을 비롯한 외국어를 표현 할 수 있도록 메시지 리소스 파일의 메시지를 가져와 화면에 출력

 

애플리케이션 컨텍스트 ( application context) : 빈 객체의 생성과 관계 설정, 사용, 제거 등의 기능을 담당하는 컨테이너. ( MessageSource 인터페이스의 구현체 지원)

 

servlet-context.xml ( 스프링 MVC 설정 파일) 에 MessageSource 인터페이스의 구현체를 빈 객체로 등록하면 애플리케이션 컨텍스트에 접근하여 원하는 메시지를 가져올 수 있다.

 

<bean id="messageSource"
	class="org.springframework.context.support.MessageSource 구현체">
    <property name="basename" value = " 메시지 리소스 파일"/>
    <property name="defaultEncoding" value="인코딩"/>
    ...
    
</bean>

 

아래는 MessagSource 구현체의 유형

유형 설명
ResourceBundleMessageSource ResourceBundle과 MessageFormat 클래스 기반으로 만들어졌으며, 특정 이름으로 메시지 접근
ReloadableResourceBundleMessageSource <property name="cacheSeconds" value="2"/> 프로퍼티 설정으로 다시 시작하지 않고 애플리케이션 실행 도중에 메시지 정의를 다시 로드 가능
<beans: bean id = "messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
	<beans:property name = "basename" value="messages"/>
</beans:bean>

 

 

뷰 페이지에 메시지 출력

메시지 리소스 파일에서 메시지를 가져와 뷰 페이지에 출력하려면 메시지 태그를 사용해야함.

<%@ taglib prefix="spring" uri = " http://www.springframework.org/tags "%>
 // 스프링의 태그 라이브러리 선언
 //prefix : 어느 곳이든 태그 이름이 spring 인 라이브러리의 태그를 사용함을 의미
 //<spring:message> 태그를 사용하여 메시지 리소스 파일에서 메시지를 가져와 뷰 페이지에 출력

 

<spring: Message > 태그의 속성

속성 설명
arguments 부가적인 인자를 넘겨줌. 콤마로 구분된 문자열, 객체 배열, 객체 하나를 넘긴다
argumentSeparator 넘겨줄 인자의 구분자를 설정. 기본값은 콤마
code 추출할 메시지의 키를 지정. 지정하지 않으면 text 속성에 입력한 값이 출력

htmlEscape 기본값은 false
message 스프링 MVC 에서 유효성 검사를 거친 오류 메시지를 간단하게 보여줄 때 사용
scope 결과 값을 변수에 지정할때 변수 번위 ( page, request,session, application ) 를 정함
text 해당 code 속성에서 가져온 값이 없을 때 기본으로 보여주는 묹열. 빈값이면 null
var 결과 값을 저장할 때 사용. 빈 값이면 JSP에 그대로 출력

12.3

12.3.1 LocaleResolver 환경 설정

 

LocaleResolver로 웹 브라우저의 로케일을 추출해서 알맞은 언어를 선택하여 메시지를 출력함

디스패치 서블릿은 웹 요청이 들어오면 localeresolver 를 검색하고, 로케일 개체가 검색된다면 이를 이용해 로케일을 설정

유형 설명
AcceptHeaderLocaleResolver 웹 브라우저에 설정된 기본 로케일 사용
CookieLocaleResolver 쿠키를 이용한 로케일 정보를 사용함.
SessionLocaleResolver 세션을 이용한 로케일 정보 사용
FixedLocaleResolver 특정 로케일을 지정

Cookie/Session LocaleResolver 는 웹 브라우저의 로케일에 따라 원하는 언어 선택하여 서비스 가능

Fixed LocaleResolver 웹 브라우저의 로케일과는 상관없이 지정된 언어만 서비스 함

< CookieLocaleResolver 빈 등록 설정>

<beans:bean id="localeResolver"
	class="org.springframework.web.sevlet.i18n.CookieLocaleResolver">
    <beans:property name="cookieName" vlaue="clientlanguage"/>
    <beans:property name="cookieMaxAge" value="100000"/>
    <beans:property name="defaultLocale" value="ko"/>
    </beans:bean>

-> 쿠키이름은 clientlanguage 로 쿠키 유지시간은 100000으로 설정했음. 쿠키 유지 시간은 기본값 -1 로 설정하면 웹 브라우저를 닫을 때 쿠키를 유지하지 않고 삭제함. defaultLocale 프로머티가 없다면 웹 브라우저의 언어설정을 따름

 

 LocaleChangeinterceptor 을 이용한 로케일 변경

LocaleChangeInterceptor 클래스를 사용하면 로케일을 변경하는 별도이 컨트롤러 클래스를 구현할 필요없이 메시지를 해당 언어로 변경 가능.( 웹 요청의 매개변수를 사용해 로케일 변경)

 

LocaleChangeInterceptor 클래스는 HandlerInterceptor 로 <interceptors> 요소에 등록만 하면 디스패처 서블릿이 컨트롤러에 접근 할 때 응답을 가로채서 LocaleChangeInterceptor적용가능

 

//LocaleChangeInterceptor 빈 등록 설정

<interceptors>
	<beans:bean id = "localeChangeInterceptor"
    	class = "org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <beans:property name = "paramName" value="language"/>
        </beans:bean>
        </interceptors>

 

'공부 > Backend' 카테고리의 다른 글

Spring boot  (0) 2024.01.14
Spring boot 3장  (0) 2023.12.30
SQL 레벨업 9장 , 10장  (2) 2023.12.02
SQL 레벨업 - 8장  (1) 2023.11.25
SQL 레벨업 - 7장  (1) 2023.11.18