SpringBoot | 第十六章:web應用開發

前言

前面講了這麼多章節,都沒有涉及到前端web和後端交互的部分。由於做者所在公司是採用先後端分離方式進行web項目開發了。因此都是後端提供api接口,前端根據api文檔或者服務自行調用的。後臺也有讀者說爲什麼沒有關於web這部分的集成文章。本章節就主要講解下如何渲染頁面的。css

一點知識

咱們知道,在web開發時,通常都會涉及到不少的靜態資源,如jsimagecss文件等。html

SpringBoot的默認的靜態文件目錄是:前端

  • /static
  • /public
  • /resources
  • /META-INF/resources

默認靜態文件目錄

因此通常上咱們只須要把靜態文件放入前面的四個任一一個便可。默認都放在static下,對應路徑即爲:src/main/resources/staticjava

而從官網文檔裏也能夠獲悉,爲了實現動態的html,SpringBoot是經過模版引擎進行頁面結果渲染的,目前(1.5.15)版本的提供默認配置的模版引擎主要爲:git

模版引擎

對於模版引擎而言,SpringBoot默認存放模版文件的路徑爲src/main/resources/templates,固然也能夠經過配置文件進行修改的。由於不一樣的模版引擎對應的配置屬性是不同,因此在具體講解模版引擎時,會提到的。github


固然了,使用jsp也是能夠的,但官方已經不建議使用JSP,本文也會講解下SpringBootJSP的支持的,比較有不少老的項目仍是使用JSP居多的。web


知道了以上的一些默認配置和知識點後,就能夠進行模版引擎的集成使用了。本章節主要講解下經常使用的FreeMarkerThymeleafJSP三個的集成和使用,其餘的基本用法都同樣,就是各模版引擎的語法的差別了。spring

FreeMarker支持

FreeMarker是一款模板引擎: 即一種基於模板和要改變的數據,並用來生成輸出文本(HTML網頁,電子郵件,配置文件,源代碼等)的通用工具。apache

示例

0.POM依賴後端

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

1.application.properties配置加入相關配置:

# 緩存配置 開發階段應該配置爲false 由於常常會改
spring.freemarker.cache=false

# 模版後綴名 默認爲ftl
spring.freemarker.suffix=.html

# 文件編碼
spring.freemarker.charset=UTF-8

# 模版加載的目錄
spring.freemarker.template-loader-path=classpath:/templates/

# 配置
# locale    該選項指定該模板所用的國家/語言選項
# number_format    指定格式化輸出數字的格式:currency、
# boolean_format    指定兩個布爾值的語法格式,默認值是true,false
# date_format,time_format,datetime_format    定格式化輸出日期的格式
# time_zone    設置格式化輸出日期時所使用的時區
# 數字 千分位標識
spring.freemarker.settings.number_format=,##0.00

題外話:詳細的配置可參見org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties類,或者直接IDE直接配置文件點擊查看。

2.編寫控制層

FreemarkerController.kava:

//由於是返回頁面 因此不能是@RestController
@Controller
@RequestMapping("/freemarker")
public class FreemarkerController {
    
    //正常和springmvc設置返回參數是意義的用法了
    @GetMapping("/map")
    public String index(String name,ModelMap map) {
        map.addAttribute("name", name);
        map.addAttribute("from", "lqdev.cn");
        //模版名稱,實際的目錄爲:src/main/resources/templates/freemarker.html
        return "freemarker";
    }
    
    @GetMapping("/mv")
    public String index(String name,ModelAndView mv) {
        mv.addObject("name", name);
        mv.addObject("from", "lqdev.cn");
        //模版名稱,實際的目錄爲:src/main/resources/templates/freemarker.html
        return "freemarker";
    }
}

3.編寫模版文件

freemarker.html:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>freemarker簡單示例</title>
</head>
<body>
<h1>Hello Freemarker</h1>
<!-- 這裏注意:默認變量都不能爲null的, 當參數爲null時,會發生異常的 -->
<!-- 這裏後面幾個"!"避免下,這樣就是空白了 -->
<h2>名稱:${name!},來自:${from}</h2>
</body>
</html>

4.啓動應用,訪問:http://127.0.0.1:8080/freemarker/mv?name=oKong 或者 http://127.0.0.1:8080/freemarker/map?name=oKong 就能查看頁面了。


關於一些Freemarker的語法這裏就不說明了,你們可到官網查看下:https://freemarker.apache.org/docs/index.html或者,中文參考(可能版本不是最新):http://freemarker.foofun.cn/toc.html


Thymeleaf支持

Thymeleaf是一個XML/XHTML/HTML5模板引擎,可用於Web與非Web環境中的應用開發。Thymeleaf的主要目標在於提供一種可被瀏覽器正確顯示的、格式良好的模板建立方式,所以也能夠用做靜態建模。你可使用它建立通過驗證的XML與HTML模板。相對於編寫邏輯或代碼,開發者只需將標籤屬性添加到模板中便可。接下來,這些標籤屬性就會在DOM(文檔對象模型)上執行預先制定好的邏輯。

0.pom依賴

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

1.application.properties配置加入相關配置:

# 啓用緩存:建議生產開啓
spring.thymeleaf.cache=false 
# 建議模版是否存在
spring.thymeleaf.check-template-location=true 
# Content-Type 值
spring.thymeleaf.content-type=text/html 
# 是否啓用
spring.thymeleaf.enabled=true 
# 模版編碼
spring.thymeleaf.encoding=UTF-8 
# 應該從解析中排除的視圖名稱列表(用逗號分隔)
spring.thymeleaf.excluded-view-names= 
# 模版模式
spring.thymeleaf.mode=HTML5 
# 模版存放路徑
spring.thymeleaf.prefix=classpath:/templates/ 
# 模版後綴
spring.thymeleaf.suffix=.html

2.編寫控制層

ThymeleafController.java:

@Controller
@RequestMapping("/thymeleaf")
public class ThymeleafController {

    // 正常和springmvc設置返回參數是意義的用法了
    @GetMapping("/map")
    public String index(String name, ModelMap map) {
        map.addAttribute("name", name);
        map.addAttribute("from", "lqdev.cn");
        // 模版名稱,實際的目錄爲:src/main/resources/templates/thymeleaf.html
        return "thymeleaf";
    }

    @GetMapping("/mv")
    public ModelAndView index(String name) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("name", name);
        mv.addObject("from", "lqdev.cn");
        // 模版名稱,實際的目錄爲:src/main/resources/templates/thymeleaf.html
        mv.setViewName("thymeleaf");
        return mv;
    }
}

3.編寫模版文件

thymeleaf.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>thymeleaf簡單示例</title>
</head>
<body>
<h1>Hello thymeleaf</h1>
<!-- 這裏注意:拼接時 變量要單獨使用${param},其餘的常量使用''包裹 -->
<h2 th:text="'名稱:'+${name}+',來自:'+${from}">默認值</h2>
</body>
</html>

4.啓動應用,訪問:http://127.0.0.1:8080/thymeleaf/mv?name=oKong 或者 http://127.0.0.1:8080/thymeleaf/map?name=oKong 就能查看頁面了。

JSP支持

雖然SpringBoot官方已經不建議使用jsp了。但在一些老的項目遷移時,jsp的支持是毋庸置疑的。因此仍是須要兼容的。。

0.pom依賴加入

<!-- spring boot 內置tomcat jsp支持 -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>

1.application.properties配置加入相關配置:

#jsp 支持
spring.mvc.view.suffix=.jsp
spring.mvc.view.prefix=/WEB-INF/jsp/

2.編寫控制層

JspController.java

@Controller
@RequestMapping("/jsp")
public class JspController {
    
    //正常和springmvc設置返回參數是意義的用法了
        @GetMapping("/map")
        public String index(String name,ModelMap map) {
            map.addAttribute("name", name);
            map.addAttribute("from", "lqdev.cn");
            //模版名稱,實際的目錄爲:src/main/webapp/jsp/index.html
            return "index";
        }
        
        @GetMapping("/mv")
        public ModelAndView index(String name) {
            ModelAndView mv = new ModelAndView();
            mv.addObject("name", name);
            mv.addObject("from", "lqdev.cn");
            //模版名稱,實際的目錄爲:src/main/webapp/jsp/index.html
            mv.setViewName("index");
            return mv;
        }
}

3.webapp/WEB-INF/jsp目錄下編寫jsp文件

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charsetUTF-8">
<title>jsp示例</title>
</head>
<body>
<h1>Hello Jsp</h1>
<h2 >名稱:${name},來自:${from}</h2>
</body>
</html>

5.啓動應用,訪問:http://127.0.0.1:8080/jsp/mv?name=oKong 或者 http://127.0.0.1:8080/jsp/map?name=oKong 就能查看頁面了。


這裏須要注意:在使用spring-boot-maven-plugin打包插件時,默認狀況下打包的應用時訪問不了jsp目錄文件的,須要把版本修改成1.4.2.RELEASE版本,同時pom中加入resource配置:

<resources>
    <!-- 打包時將jsp文件拷貝到META-INF目錄下 -->
    <resource>
        <!-- 指定resources插件處理哪一個目錄下的資源文件 -->
        <directory>src/main/webapp</directory>
        <!--注意這次必需要放在此目錄下才能被訪問到 -->
        <targetPath>META-INF/resources</targetPath>
        <includes>
            <include>**/**</include>
        </includes>
    </resource>
<!--     <resource>
          指定resources插件處理哪一個目錄下的資源文件
        <directory>src/main/resources/static</directory>
        注意這次必需要放在此目錄下才能被訪問到
        <targetPath>META-INF/resources/static</targetPath>
        <includes>
            <include>**/**</include>
        </includes>
    </resource> -->
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/**</include>
        </includes>
<!--         <excludes>
           <exclude>src/main/resources/static/**</exclude>
        </excludes> -->
        <filtering>false</filtering>
    </resource>
</resources>

相關資料

  1. https://docs.spring.io/spring-boot/docs/1.5.14.RELEASE/reference/htmlsingle
  2. http://www.javashuo.com/article/p-tgyjvdup-ga.html

總結

本章節主要是講解了利用模版引擎進行動態頁面實現功能。對於有此須要的同窗能夠去看下使用的模版引擎的相關使用教程,這裏就很少加闡述了,畢竟目前工做如今用這個的機會比較少了,也只是知道個大概使用,具體一些深刻的使用仍是看具體的官方文檔吧!

最後

目前互聯網上不少大佬都有SpringBoot系列教程,若有雷同,請多多包涵了。本文是做者在電腦前一字一句敲的,每一步都是實踐的。若文中有所錯誤之處,還望提出,謝謝。

老生常談

  • 我的QQ:499452441
  • 公衆號:lqdevOps

公衆號

我的博客:http://blog.lqdev.cn

完整示例:https://github.com/xie19900123/spring-boot-learning/tree/master/chapter-16

原文地址:https://blog.lqdev.cn/2018/08/07/springboot/chapter-sixteen/

相關文章
相關標籤/搜索