1. 程式人生 > >我的第二個springboot專案 web+freemarker

我的第二個springboot專案 web+freemarker

上一篇文章講了,建立了第一個springboot的專案,現在講一下springboot的web+freemarker的專案;

1、首先引入依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
            <version>${spring.boot.version}</version>
        </dependency>

2、建立一個Application的類,用以啟動web
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Created by LK on 2016/5/7.
 */
@SpringBootApplication
public class SampleWebFreeMarkerApplication {
    public static void main(String[] args) {
        SpringApplication.run(SampleWebFreeMarkerApplication.class,args);
    }
}

3、建立一個Controller類,用來定向到view
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

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

/**
 * Created by LK on 2016/5/7.
 */
@Controller
public class WebContrpller {
    @Value("${application.message:1234556677}")
    private String message = "hi,hello world......";

    @RequestMapping("/")
    public String web(Map<String,Object> model){
        model.put("time",new Date());
        model.put("message",this.message);
        return "web";//返回的內容就是templetes下面檔案的名稱
    }
}

4、在resources目錄下建立templates資料夾,資料夾裡面存放兩個模板檔案

4.1 error.ftl

<!DOCTYPE html>

<html lang="en">

<body>
	Something wrong: ${status} ${error}
</body>

</html>

4.2 web.ftl
<!DOCTYPE html>

<html lang="en">

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

</html>


5、啟動 SampleWebFreeMarkerApplication ,在瀏覽器上面輸入 http://127.0.0.1:8080/ 即可輸出頁面如下: