2 분 소요

 인프런 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술편을 학습하고 정리한 내용 입니다.

웹 애플리케이션에 메시지 적용하기

실제 웹 애플리케이션에 메시지를 적용해 보자.

먼저 messages.properties에 등록하자.

1
2
3
4
5
6
7
8
9
10
11
12
label.item=상품  
label.item.id=상품 IDlabel.item.itemName=상품명  
label.item.price=가격  
label.item.quantity=수량  
  
page.items=상품 목록  
page.item=상품 상세  
page.addItem=상품 등록  
page.updateItem=상품 수정  
  
button.save=저장  
button.cancel=취소

타임리프 메시지 적용

타임리프의 메시지 표현식 #{...}을 사용하면 스프링의 메시지를 편리하게 조회할 수 있다.

예를 들어서 방금 등록한 상품이라는 이름을 조회하려면 #{label.item}이라고 하면 된다.

렌더링 전

1
<div th:text="#{label.item}"></h2>

렌더링 후

1
<div>상품</h2>

타임리프 템플릿 파일에 메시지를 적용해보자.

적용 대상 : addForm.html, editForm.html, item.html, items.html

addForm.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<!DOCTYPE HTML>  
<html xmlns:th="http://www.thymeleaf.org">  
<head>  
    <meta charset="utf-8">  
    <link th:href="@{/css/bootstrap.min.css}"  
          href="../css/bootstrap.min.css" rel="stylesheet">  
    <style>  
        .container {  
            max-width: 560px;  
        }  
    </style>  
</head>  
<body>  
  
<div class="container">  
  
    <div class="py-5 text-center">  
        <h2 th:text="#{page.addItem}">상품 등록 폼</h2>  
    </div>  
  
    <form action="item.html" th:action th:object="${item}" method="post">  
        <div>  
            <label for="itemName" th:text="#{label.item.itemName}">상품명</label>  
            <input type="text" id="itemName" th:field="*{itemName}" class="form-control" placeholder="이름을 입력하세요">  
        </div>  
        <div>  
            <label for="price" th:text="#{label.item.price}">가격</label>  
            <input type="text" id="price" th:field="*{price}" class="form-control" placeholder="가격을 입력하세요">  
        </div>  
        <div>  
            <label for="quantity" th:text="#{label.item.quantity}">수량</label>  
            <input type="text" id="quantity" th:field="*{quantity}" class="form-control" placeholder="수량을 입력하세요">  
        </div>  
  
        <hr class="my-4">  
  
        <div class="row">  
            <div class="col">  
                <button class="w-100 btn btn-primary btn-lg" type="submit" th:text="#{button.save}">상품 등록</button>  
            </div>  
            <div class="col">  
                <button class="w-100 btn btn-secondary btn-lg"  
                        onclick="location.href='items.html'"  
                        th:onclick="|location.href='@{/message/items}'|"  
                        th:text="#{button.cancel}"  
                        type="button">취소</button>  
            </div>  
        </div>  
  
    </form>  
  
</div> <!-- /container -->  
</body>  
</html>
1
2
3
<div class="py-5 text-center">  
        <h2 th:text="#{page.addItem}">상품 등록 폼</h2>  
</div>  

이런 식으로 #{page.addItem}으로 메시지 프로퍼티 값을 가져와서 페이지 이름에 적용 시켰다.

1
2
3
<label for="itemName" th:text="#{label.item.itemName}">상품명</label>  
  ...
<label for="quantity" th:text="#{label.item.quantity}">수량</label>

라벨에도 똑같이 적용했다.

1
2
3
4
5
6
7
8
<button class="w-100 btn btn-primary btn-lg" type="submit" th:text="#{button.save}">상품 등록</button>
  ...

<button class="w-100 btn btn-secondary btn-lg"  
                        onclick="location.href='items.html'"  
                        th:onclick="|location.href='@{/message/items}'|"  
                        th:text="#{button.cancel}"  
                        type="button">취소</button>

버튼도 가능하다.

프로퍼티로 바뀐 걸 보기 위해 프로퍼티에 아무 숫자나 더 붙혀 줬다. 메시지 프로퍼티 따라 잘 바뀐다.

나머지 editForm.html, item.html, items.html 도 잘 바꿔주면 된다.

다 프로퍼티를 의존해서 바뀌게 되었다.

참고로 파라미터는 다음과 같이 사용할 수 있다.

1
hello.name=안녕 {0}
1
<p th:text="#{hello.name(${item.itemName})}"></p>

웹 애플리케이션에 국제화 적용하기

이번에는 웹 애플리케이션에 국제화를 적용해 보자.

messages_en.properties

1
2
3
4
5
6
7
8
9
10
11
12
13
label.item=Item  
label.item.id=Item ID  
label.item.itemName=Item Name  
label.item.price=price  
label.item.quantity=quantity  
  
page.items=Item List  
page.item=Item Detail  
page.addItem=Item Add  
page.updateItem=Item Update  
  
button.save=Save  
button.cancel=Cancel

자 이제 메세지화를 다 했기 때문에, 국제화는 끝났다!

앞에서 템플릿 파일에는 모두 #{...}를 통해서 메시지를 사용하도록 적용 해두었기 때문이다.

크롬에 설정 → 언어 : 영어(가장 위로 이동)로 바꾸고 확인해 보자.

끝났다…

웹 브라우저 언어 설정 값을 변경하면 요청 시 Accept-Language의 값이 변경된다.

Accept-Language는 클라이언트가 서버에 기대하는 언어 정보를 담아서 요청하는 HTTP 요청 헤더이다.

스프링의 국제화 메시지 선택

메시지 기능은 Locale정보를 알아야 선택할 수 있다.

결국 스프링도 Locale정보를 알아야 언어를 선택할 수 있는데, 스프링은 언어 선택 시 기본으로 Accept-Language 헤더의 값을 사용한다.

LocaleResolver

스프링은 Locale선택 방식을 변경할 수 있도록 LocaleResolver라는 인터페이스를 제공하는데, 스프링 부트는 기본으로 Accept-Language를 활용하는 AcceptHeaderLocaleResolver를 사용한다.

LocaleResolver 인터페이스

1
2
3
4
5
public interface LocaleResolver {  
    Locale resolveLocale(HttpServletRequest request);  
  
    void setLocale(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Locale locale);  
}

LocaleResolver 변경

만약 Locale선택 방식을 변경하려면 LocaleResolver의 구현체를 변경해서 쿠키나 세션 기반의 Locale 선택 기능을 사용할 수 있다.

예를 들어서 고객이 직접 Locale을 선택하도록 하는 것이다.

댓글남기기