當前位置:
首頁 > 知識 > SpringBoot | 第十六章:web 應用開發

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

(點擊

上方公眾號

,可快速關注)




來源:oKong ,


blog.lqdev.cn/2018/08/07/springboot/chapter-sixteen/




前言



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




一點知識




我們知道,在web開發時,一般都會涉及到很多的靜態資源,如js、image、css文件等。




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





  • /static



  • /public



  • /resources



  • /META-INF/resources







所以一般上我們只需要把靜態文件放入前面的四個任一一個即可。默認都放在static下,對應路徑即為:src/main/resources/static。



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






  • FreeMarker



  • Groovy



  • Thymeleaf



  • Mustache







對於模版引擎而言,SpringBoot默認存放模版文件的路徑為src/main/resources/templates,當然也可以通過配置文件進行修改的。因為不同的模版引擎對應的配置屬性是不一樣,所以在具體講解模版引擎時,會提到的。



當然了,使用jsp也是可以的,但官方已經不建議使用JSP了,本文也會講解下SpringBoot下JSP的支持的,比較有很多老的項目還是使用JSP居多的。




知道了以上的一些默認配置和知識點後,就可以進行模版引擎的集成使用了。本章節主要講解下常用的FreeMarker、Thymeleaf及JSP三個的集成和使用,其他的基本用法都一樣,就是各模版引擎的語法的差異了。




FreeMarker支持




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






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. https://blog.csdn.net/qq_34665539/article/details/74783910




總結




本章節主要是講解了利用模版引擎進行動態頁面實現功能。對於有此需要的同學可以去看下使用的模版引擎的相關使用教程,這裡就不多加闡述了,畢竟目前工作現在用這個的機會比較少了,也只是知道個大概使用,具體一些深入的使用還是看具體的官方文檔吧!




最後




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




系列






  • SpringBoot | 第一章:第一個 SpringBoot 應用



  • SpringBoot | 第二章:lombok 介紹及簡單使用



  • SpringBoot | 第三章:springboot 配置詳解



  • SpringBoot | 第四章:日誌管理



  • SpringBoot | 第五章:多環境配置



  • SpringBoot | 第六章:常用註解介紹及簡單使用



  • SpringBoot | 第七章:過濾器、監聽器、攔截器



  • SpringBoot | 第八章:統一異常、數據校驗處理



  • SpringBoot | 第九章:Mybatis-plus 的集成和使用



  • SpringBoot | 第十章:Swagger 2 的集成和使用



  • SpringBoot | 第十一章:Redis 的集成和簡單使用



  • SpringBoot | 第十二章:RabbitMQ 的集成和使用



  • SpringBoot | 第十三章:測試相關 ( 單元測試、性能測試 )



  • SpringBoot | 第十四章:基於 Docker 的簡單部署



  • SpringBoot | 第十五章:基於 Postman 的 RESTful 介面測試





    【關於投稿】




    如果大家有原創好文投稿,請直接給公號發送留言。




    ① 留言格式:


    【投稿】+《 文章標題》+ 文章鏈接

    ② 示例:


    【投稿】《不要自稱是程序員,我十多年的 IT 職場總結》:http://blog.jobbole.com/94148/

    ③ 最後請附上您的個人簡介哈~






    看完本文有收穫?請轉發分享給更多人


    關注「ImportNew」,提升Java技能


    喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

    本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


    請您繼續閱讀更多來自 ImportNew 的精彩文章:

    塵埃落定,JDK 11 確定將引入 Shebang #! 符號
    SpringBoot | 第十三章:測試相關 ( 單元測試、性能測試 )

    TAG:ImportNew |