티스토리 뷰

스프링은 기본적인 메세지 관리 기능을 제공한다.

 

메시지 관리 기능을 사용하려면 스프링이 제공하는 MessageSource 를 스프링 빈으로 등록하면 되는데, MessageSource는 인터페이스이다. 따라서 구현체인 'ResourceBundelMessageSource'를 스프링 빈으로 등록하면 된다.

 

직접등록

@SpringBootApplication
public class ItemServiceApplication {

	public static void main(String[] args) {
		SpringApplication.run(ItemServiceApplication.class, args);
	}

	//메세지 직접등록
	@Bean
	public MessageSource messageSource(){
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		messageSource.setBasenames("messages","errors"); //resources안에 messages,errors을 자동으로 읽어온다
		messageSource.setDefaultEncoding("utf-8");
		return messageSource;
	}
}

 

직접 등록하지 않아도 스프링 부트에서는 자동으로 등록된다.

 

resources/application.properties 안에 아래처럼 등록하여 사용 할 수 있다.

spring.messages.basename=masseges,config,i18n.message

 

 

java에서 사용

    @Autowired
    MessageSource ms;

    @Test
    void helloMessage(){
        String result = ms.getMessage("dd", null, null);
        assertThat(result).isEqualTo("??");
    }

    @Test
    void notFoundMessageCode(){
        assertThatThrownBy(()-> ms.getMessage("no_code",null,null)).isInstanceOf(NoSuchMessageException.class);
    }

    @Test
    void notFoundMessageCodeDefaultMessage(){
        String result = ms.getMessage("no_code",null,"기본 메시지", null);
        assertThat(result).isEqualTo("기본 메시지");
    }

    @Test
    void argumentMessage(){
        String result = ms.getMessage("hello.name",new Object[]{"spring"},null);
        assertThat(result).isEqualTo("안녕 Spring");
    }

    @Test
    void defaultLang(){
        assertThat(ms.getMessage("hello",null, Locale.ENGLISH)).isEqualTo("hello");
    }

 

 

thymleaf에서 사용

   <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>
        </form>

'dev_공부일지 > spring boot + intelliJ' 카테고리의 다른 글

BindingResult thymleaf 2  (0) 2023.05.13
Spring LocalResolver  (0) 2023.05.08
thymleaf 연산  (0) 2023.05.03
thymleaf 리터럴  (0) 2023.05.03
thymeleaf 편의객체 접근  (0) 2023.04.07
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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
글 보관함