LoginSignup
0
0

More than 3 years have passed since last update.

Spring MVCがひとつ以上のテンプレートエンジン一緒に利用できる

Last updated at Posted at 2019-09-18

この例は、Thymeleafテンプレートエンジンを使っているSpring MVCプロジェクトに、もうひとつFreeMarkerテンプレートエンジンを加え、FreeMarkerテンプレートエンジンを使う'hello world'ウェブページを作ること。

まずはサンプルアプリケーションのソースコードを取り、pom.xmlにFreeMarkerテンプレートエンジンをプロジェクトに入れる。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

FreeMarkerテンプレートを作成する。名前は'resources/templates/public/freemarker_test.ftl'

<html>
<head>
  <title>${title}</title>
</head>
<body>
  <div>${body}</div>
</body>
</html>

info.saladlam.example.spring.noticeboard.controller.PublicControllerコントローラに新しいメソッドを入れる。

public class PublicController {
    // ...
    @GetMapping("/freemarker_test")

    public String freemarkerTest(Model model) {
        model.addAttribute("title", "FreeMarker test page");
        model.addAttribute("body", "Hello world!");

        return "public/freemarker_test";
    }
}

アプリケーションを起動し、ブラウザでhttp://localhost:8080/freemarker_testをアクセスする。すると'Hello world!'が見える。

何があった?

アプリケーションを起動すると、下のorg.springframework.web.servlet.ViewResolver BeanはSpring Bootが作った。
- org.thymeleaf.spring5.view.ThymeleafViewResolver
- org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver

org.springframework.web.servlet.DispatcherServletインスタンスが作られて、初期化する時、メソッドinitViewResolvers()が呼ばれった。

        if (this.detectAllViewResolvers) {
            // Find all ViewResolvers in the ApplicationContext, including ancestor contexts.
            Map<String, ViewResolver> matchingBeans =
                    BeanFactoryUtils.beansOfTypeIncludingAncestors(context, ViewResolver.class, true, false);
            if (!matchingBeans.isEmpty()) {
                this.viewResolvers = new ArrayList<>(matchingBeans.values());
                // We keep ViewResolvers in sorted order.
                AnnotationAwareOrderComparator.sort(this.viewResolvers);
            }
        }
        // ...

上のコードに示したのは、全てのViewResolver BeanはBeanFactoryからもらう。

PublicControllerクラスのfreemarkerTest()メソッドが呼ばれ、文字列'public/freemarker_test'が返す。この文字列はorg.thymeleaf.spring5.view.ThymeleafViewResolverで調べ、この名前のThymeleafテンプレートが定義されないため、nullが返した。そしてorg.springframework.web.servlet.view.freemarker.FreeMarkerViewResolverで調べ、org.springframework.web.servlet.Viewインタフェースのインスタンスが返した。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0