thymeleaf+spring mvc

2014-01-02T00:00:00+00:00 Java Spring Framework

タイトルどおりでSpring WebMVCでJSPを使わずにthymeleafを使ってやるってだけ。まぁドキュメント(但しSpring3)を見れば良いだけなので、ざっくり行きます

まぁようはspring-web-servlet.xml(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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <context:component-scan base-package="sample" />
    <mvc:annotation-driven />

    <bean
        id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource"
        p:basename="applicationMessages" />

    <bean
        id="templateResolver"
        class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">

        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".html" />
        <property name="templateMode" value="HTML5" />
        <property name="characterEncoding" value="UTF-8" />

    </bean>

    <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring4.SpringTemplateEngine">
                <property name="templateResolver" ref="templateResolver" />
            </bean>
        </property>
        <property name="order" value="1" />
        <property name="characterEncoding" value="UTF-8" />
    </bean>
</beans>

はい、終わり。あとは

package sample;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/sample")
public class SampleController {

    @RequestMapping
    public void index(ModelMap model) {
        model.addAttribute("message", "hoge fuga foobar");
    }
}

みたいなコントローラー作って、/WEB-INF/views/sample.html (この場合 http://localhost:8080/context_name/sample.action でアクセスするのでsample.htmlになる)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
    <span th:text="${message}"></span>
    <span th:text="#{message}"></span>
</body>
</html>

まぁコントローラーから値ぶっこんだコンテキスト内データとメッセージバンドルなデータを出力しているだけ。で上記でorg.springframework.context.support.ResourceBundleMessageSourceを設定しているのでそこから#{}記法なメッセージバンドルなデータ取得はそこから参照する事になる模様で

とりまぁこんなもんで、Spring WebMVCでJSP使わずにthymeleafを利用する事も出来るって事で

Spring WebMVCをやってみる (17) - Formatter - thymeleaf