본문 바로가기
Backend/Spring

[Spring & Boot] Message 사용법

by unknownomad 2022. 3. 24.

메시지(Message)

정의

  • 메시지 코드로 메시지 콘텐츠를 호출
  • message.properties 파일에서 관리(application.properties와 유사함)

구조

//{messageCode}={messageContent}
labl.cate="Category"
labl.mng="Management"

사용 목적

  • 클라이언트 단에서 보여주는 문자 관리
  • 클라이언트 언어 설정에 따른 문자 관리(다국어화)
  • 에러 코드 및 에러 메시지 관리

메시지 설정

1. Spring

  • MessageSource의 구현체인 ResourceBundleMessageSource를 직접 Bean에 등록해야 함
@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource MS = new ResourceBundleMessageSourcce();
    
    //MessageSource 인코딩 방식 설정
    MS.setDefaultEncoding("utf-8");
    
    //메시지 관리할 파일명 설정
    //message로 지정 시 src/main/resources/messages.properties로 설정
    MS.setBasenames("messages");
    
    return MS;
}

1.1. HTML 상에서 사용법

<!-- spring message 형식 -->
<spring:message code="codeName"/> <!-- messages.properties에 지정된 코드명 사용 -->

2. Spring Boot

  • ResourceBundleMessageSource가 이미 bean으로 등록되어 있음
    ➡ application.properties에서 Message 관리할 파일 경로만 등록해주면 됨

2.1. application.properties 설정

  • MessageSourceAutoConfiguration을 사용한 INTERNATIONALIZATION 설정에 따름
# INTERNATIONALIZATION (MessageSourceAutoConfiguration)
spring.messages.always-use-message-format=false # Set whether to always apply the MessageFormat rules, parsing even messages without arguments.
spring.messages.basename=messages # Comma-separated list of basenames, each following the ResourceBundle convention.
spring.messages.cache-seconds=-1 # Loaded resource bundle files cache expiration, in seconds. When set to -1, bundles are cached forever.
spring.messages.encoding=UTF-8 # Message bundles encoding.
spring.messages.fallback-to-system-locale=true # Set whether to fall back to the system Locale if no files for a specific Locale have been found.

2.2. 상기 application.properties 코드에서 메시지 설정하기

  • spring.messages.basename 설정
  • 어떤 파일을 messages 관리 파일로 지정할지 설정
  • ',' 이용해 여러 경로 설정 가능(아무 경로도 설정하지 않을 경우 default로 messages.properties 참조)
//application.properties
spring.messages.basename=message,config.i18n.messages
spring.messages.encoding=UTF-8

/*
주의점
파일 이름에 '.' 넣으면 안 됨
spring.messages.basename 설정을 파싱하는 코드는 '.'를 기준으로 파일 경로를 나누기 때문
(일반적인 파일 경로의 '/'와 같은 의미)
*/

3. 메시지 추가(Spring & Spring Boot)

//messages.properties
title=메인홈
hi=안녕하세요.
arg=저희 웹사이트는 {0}년도에 만들어졌습니다.
...

 


메시지 클라이언트 렌더링

1. 메시지 목적

클라이언트에 문자를 동적으로 표시하기 위함

(에러코드는 메시지의 특수한 경우로, 다른 사용 방법이 존재함)

 

2. 문자를 클라이언트에 표시하는 방법

2.1. thymeleaf 활용 예제

  • thymeleaf: 서버사이드 렌더링 템플릿
  • application.properties, message.properties 설정 그대로 유지 ➡ html 파일 및 Controller 추가
//의존성
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
}
//Controller
@Controller
public class indexController {

    @GetMapping("/index")
    public String indexMsgRender(Model model) {
    
        model.addAttribute("year", 1999);
        return "/index";
    }
}
<!-- templates/index.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>
<body>
    <sapn th:text="#{title}">test1</sapn><br/>
    <sapn th:text="#{hi}">test2</sapn><br/>
    <sapn th:text="#{arg(${year})}">test3</sapn>
</body>
</html>

 

  • Spring Boot의 Application 실행 ➡ localhost:8080/index 접속 시 결과
<!-- 결과물 -->
<!-- message code에 맞는 content가 출력됨 -->

메인홈
안녕하세요
저희 웹사이트는 1999년도에 만들어졌습니다.

<!-- test1, test2, test3은 출력되지 않음 -->

 

2.2. thymeleaf 메시지 매칭 방법

//메시지 매칭
#{message code}

//arg 매칭
#{message code (${model attribute})}

메시지 다국어화

1. 정의 

목적

  • 클라이언트의 언어 설정에 따른 메시지 표현

Interceptor

  • 클라이언트의 언어 설정을 읽어오는 역할

LocaleResolver

  • 클라이언트 언어 설정을 해석해 ResourceBundleMessageSource에 전달하는 역할

 

2. 다국어화 설정

2.1. Spring

  • Interceptor, LocaleResolver, ResourceBundleMessageSource 모두 설정해야 함

2.2. Spring Boot

  • Interceptor, LocaleResolver, ResourceBundleMessageSource: 모두 내장됨
  • message 파일명으로 언어 매칭만 하면 됨
//message 관리파일 작명 규칙
messages_ko.properties
messages_en.properties
messages.jp.properties
//messages_en.properties
title=Main Page
hi=Hi
arg=Our website was created in {0}.
<!-- messages_en.properties 적용된 클라이언트 화면 -->

Main Page
Hi
Our website was created in 1999.

 


출처 : https://velog.io/@tjeong/Spring-Message-%EC%82%AC%EC%9A%A9%EB%B2%95

댓글