トッカンソフトウェア

SpringBoot MessageSource

今回はThymeleafでMessageSourceをやります。Thymeleaf基本をベースに変更部分だけ記述する ので、まずはThymeleaf基本で環境を構築してください。


ソース

messages.properties

以下の場所にmessages.propertiesというファイルを作成します。


Eclipseで以下を入力します。
				
aaa=あああ
arg=引数({0})

			
Eclipseで上記を入力すると自動的に変換され(エスケープ表記)以下のようになります。
				
aaa=\u3042\u3042\u3042
arg=\u5F15\u6570({0})

			
LoginControler.java
				
package spring.test.controller;

import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import spring.test.UserModel;

@Controller
@RequestMapping(value = "/login")
public class LoginControler {

	private final MessageSource message;

	@Autowired
	public LoginControler(MessageSource msg) {
		this.message = msg;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String loginGet(@ModelAttribute("UM") UserModel userModel, Locale locale) {

		System.out.println(message.getMessage("aaa", null, locale));
		String[] strs = { "xxx" };
		System.out.println(message.getMessage("arg", strs, locale));

		userModel.setId("初期値");
		return "login";
	}

}

			
login.html
				
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>ログイン</title>
<script type="text/javascript" th:inline="javascript">
	var msg = /*[[#{aaa}]]*/null;
	alert(msg);
</script>
</head>
<body>
	<p th:text="#{aaa}">bbb</p>
	<input type="button" th:value="#{aaa}" value="bbb" />
	<input type="submit" th:value="#{aaa}" value="bbb" />
	<p th:text="#{arg('xxx')}">bbb</p>
</body>
</html>

			


実行結果(画面)

(ダイアログ)

(コンソール)
				
あああ
引数(xxx)

			


ページのトップへ戻る