オブジェクト指向とかデザインパターンとか開発プロセスとかツールとか

satoshi's ソフトウェア開発

js






当サイトはアフィリエイト広告を利用してます。

Java

Spring bootのthymeleafを国際化する

更新日:


thymeleafでメッセージを国際化するやり方をまとめておきます。

まずメッセージリソースとなるファイルを作ります。
src/main/resources に i18n フォルダを作成し、そこに各国語対応のファイルを作ります。
とりあえず英語と日本語のファイルを作ります。

src/main/resources/i18n/messages_en.properties

helloworld=Hello World!

src/main/resources/i18n/messages_ja.properties

helloworld=こんにちは世界!

thymeleafテンプレートの中で「helloworld」をキーにしてメッセージリソースから取得します。

src/main/resources/templates/index.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
</head>
<body>
    <h1 th:text="#{helloworld}">Hello</h1>
</body>
</html>

現状では、thymeleaf はメッセージリソースがどこにあるのかを知りませんので、どこかで設定する必要があります。
このような設定は、applicationContext.xmlに記述するのが一般的みたいです。

src/main/resources/applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>i18n/messages</value>
            </list>
        </property>
    </bean>
</beans>

これで表示してくれるかと思ったら、デフォルトでは applicationContext.xml ファイルを読み込んでくれないようです。
mainメソッドを書いているクラスで、@ImportResourceアノテーションで指定してやればいいようです。

package hoge;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

@SpringBootApplication
@ImportResource("classpath:applicationContext.xml")
public class HogeApplication {

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

}

これでメッセージの国際化ができました。

しかし、タグに th:text で埋め込む方法では、HTMLタグに限られてしまいます。

JavaScript内にも国際化した文字列を埋め込みたい場合もあります。

その際は、以下のように埋め込みます。
コメント内で埋め込む感じですね。
で、コメント直後の数値や文字は、埋め込んだ文字列と置き換えられます。

let userId = /*[[${user.id}]]*/0;







-Java
-, , ,

Copyright© satoshi's ソフトウェア開発 , 2024 All Rights Reserved Powered by STINGER.