Spring Boot整合模板引擎

一、FreeMarker模板引擎

Spring Boot支持FreeMarker模板引擎,它是在Spring MVC基础上加入了自动配置的特性,在使用FreeMarker模板引擎的时候,需要在resources文件夹内建立static文件夹存放静态资源(一般包括css、images、js),还要建立一个templates文件,用于存放FreeMarker模板。

1)依赖配置



    4.0.0

    springboot.example
    springboot-freemarker
    1.0-SNAPSHOT
    jar
    springboot-freemarker
    Spring Boot整合FreeMarker

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.8.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-freemarker
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        

        
            org.webjars
            jquery
            3.2.1
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


Spring Boot对静态资源友好z支持,包括对WebJars的支持也非常友好,这里也使用了WebJars。

2)index.ftl模板




    Spring Boot Demo - FreeMarker

    



${title}

上面jquery的资源就来自于WebJars,WebJars将常见的web静态资源封装到了jar包中,这样更加方便管理和版本控制。

3)controller代码

package com.lemon.springboot.controller;

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

/**
 * @author lemon
 */
@Controller
@RequestMapping("/web")
public class WebController {

    @RequestMapping("/index")
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("title", "Hello World");
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @RequestMapping("/index1")
    public String index1(ModelMap modelMap) {
        modelMap.addAttribute("title", "Hello World!!!");
        return "index";
    }
}

注意:注解@Controller支持Model、ModelMap以及ModelAndView,如果是@RestController,将仅仅支持ModelAndView。

二、Thymeleaf引擎模板

Spring Boot默认使用的是Thymeleaf引擎模板,它的模板是HTML格式的,里面使用的th命名空间。使用方法和FreeMarker一模一样,只需要将FreeMarker的依赖改成Thymeleaf的依赖,将Thymeleaf的模板替换FreeMarker的模板即可。

1)依赖


    org.springframework.boot
    spring-boot-starter-thymeleaf

2)模板




    Spring Boot Demo - Thymeleaf
    
    
    


    

你可能感兴趣的:(Spring Boot整合模板引擎)