springboot2+freemarker簡單使用


一、src/main/resources/templates下新建welcome.ftl

<!DOCTYPE html>

<html lang="en">

<body>
    Date: ${time?date}
    <br>
    Time: ${time?time}
    <br>
    Message: ${message}
</body>

</html>

二、啟動類

package com.my.bootdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Bootdemo1Application {

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

三、controller

package com.my.bootdemo;

import java.util.Date;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {

    @GetMapping("/")
    public String welcome(Map<String, Object> model) {
        model.put("time", new Date());
        model.put("message", "yes, this is message.");
        return "welcome";
    }
}

四、pom.xml中添加配置

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

以上就是全部的配置了,application.properties中不需要任何參數,全部都是默認,啟動程序,瀏覽器輸入:http://localhost:8080/

整個過程還是比較簡單的,但由於我們項目還在使用struts2,直接要使用springboot,以上操作還是花了些時間,故記錄一下,花時間主要原因:最開始Controller使用的注解為@RestController,這就造成始終返回給頁面的都是welcome這個單詞,而不是welcome這個頁面。

@RestController = @Controller + @ResponseBody,加上@ResponseBody注解,返回的是json數據,具體實現原理后續在進行調查

 

一般配置中應該添加前端控制器在服務器時就進行初始化

spring.mvc.servlet.load-on-startup=1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM