如何快速搭建一個MCV程序?
參照spring官方例子:https://spring.io/guides/gs/serving-web-content/
一、spring mvc結合thymeleaf模板
創建maven project後,修改pom.xml文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.github.carter659</groupId> <artifactId>spring02</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> </parent> <name>spring02</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>
添加“MainController.java”這個控制器的類文件:
package com.github.carter659.spring02;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;@Controllerpublic class MainController { @GetMapping("/") public String index(Model model) { model.addAttribute("name", "劉冬"); return "index"; }}修改App.java文件
package com.github.carter659.spring02;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class App { public static void main(String[] args) { SpringApplication.run(App.class, args); }}然後在項目中右鍵進入java build path
添加文件夾“And Folder”
在main目錄下添加“resources”文件夾
修改"resources"的“Excluded”:
輸入“**”
在src/main/resources下創建“templates”文件夾,並新建一個html文件“index.html”
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>MVC</title></head><body> <p th:text="'Hello, ' + ${name} + '!'" /></body></html>輸入http://localhost:8080 檢測是否運行成功:
以上是使用thymeleaf模板做的動態頁面,那麼,如何在MVC應用中使用靜態資源呢?
二、靜態資源
在src/main/resources下新建“static”文件夾
並在其文件夾中復制進一張圖片文件
修改之前的“index.html”文件,增加img標籤
<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>MVC</title></head><body> <img src="img.png" /> <p th:text="'Hello, ' + ${name} + '!'" /></body></html>這時,立刻出現一個現象:
我們發現程序會自動熱加載,這是因為在maven中依賴了“devtools”
最後,刷新網頁,測試靜態資源是否載入
PS:spring boot主推的是thymeleaf模板,而其語言用的是xml,個人認為不是非常方便。
代碼下載:https://github.com/carter659/spring-boot-02.git
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。