spring boot 學習(配置頁面模版)

此文做記錄交流,如有不當,還望指正。

配置freemarker

SpringBoot配置freemarker非常簡單,我們只用在pom中添加freemarker依賴就ok了,SpringBoot默認的freemarker的頁面位置位于 /src/main/resources/templates下面

首先添加依賴

     <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.demo</groupId>
      <artifactId>springboot-helloword</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
      <name>springboot-helloword</name>
      <url>http://maven.apache.org</url>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <parent>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-parent</artifactId>
         <version>1.4.0.RELEASE</version>
      </parent>
      <dependencies>
        <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>


        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <scope>test</scope>
        </dependency>
      </dependencies>
    </project>

在resources下面創建templates文件夾,并且在文件夾下面創建一個hello.ftl的文件


image.png

在hello.ftl 中添加


image.png

在controller中調用頁面模版
package com.demo.springboot_helloword.web;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class HelloController {
        @RequestMapping("/hello")
        public String hello(){
            return "hello";
        }
    }

啟動項目訪問http://localhost:8080/hello看看效果

配置其他模版的方式和配置freemarker的方式是一樣的,Spring boot 支持 Thymeleaf FreeMarker Velocity Groovy Mustache

靜態資源配置

Spring Boot 默認配置的/映射到/static(或/public ,/resources,/META-INF/resources),/webjars/會映射到classpath:/META-INF/resources/webjars/。
上面的 /public /resources /META-INF/resource 都位于classpath:下面,如 /src/main/resources/static
靜態資源我們一般會放在/static 下面,
比如我們在static中創建img文件夾,后在里面放一張名為logo.png的圖片

image.png

啟動項目訪問http://localhost:8080/img/logo.png看看效果

使用WebJars

添加jquery依賴:
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>1.11.3</version>
</dependency>
然后可以如下使用:
<script type="text/javascript" src="/webjars/jquery/1.11.3/jquery.js"></script>
你可能注意到href中的1.11.3版本號了,如果僅僅這么使用,那么當我們切換版本號的時候還要手動修改href,怪麻煩的,我們可以用如下方式解決。

先在pom.xml中添加依賴:

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>webjars-locator</artifactId>
</dependency>

增加一個WebJarController

@Controller
public class WebJarController {
    private final WebJarAssetLocator assetLocator = new WebJarAssetLocator();

    @ResponseBody
    @RequestMapping("/webjarslocator/{webjar}/**")
    public ResponseEntity locateWebjarAsset(@PathVariable String webjar, HttpServletRequest request) {
        try {
            String mvcPrefix = "/webjarslocator/" + webjar + "/";
            String mvcPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
            String fullPath = assetLocator.getFullPath(webjar, mvcPath.substring(mvcPrefix.length()));
            return new ResponseEntity(new ClassPathResource(fullPath), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}

然后使用的時候按照如下方式:

<script type="text/javascript" src="/webjarslocator/jquery/jquery.js"></script>

注意:這里不需要在寫版本號了,但是注意寫url的時候,只是在原來url基礎上去掉了版本號,其他的都不能少!

靜態資源版本管理

Spring MVC 提供了靜態資源版本映射的功能。

用途:當我們資源內容發生變化時,由于瀏覽器緩存,用戶本地的靜態資源還是舊的資源,為了防止這種情況導致的問題,我們可能會手動在請求url的時候加個版本號或者其他方式。

版本號如:

<script type="text/javascript" src="/js/sample.js?v=1.0.1"></script>

Spring MVC 提供的功能可以很容易的幫助我們解決類似問題。

Spring MVC 有兩種解決方式。

注意:下面的配置方式針對freemarker模板方式,其他的配置方式可以參考。

資源名-md5 方式

例如:

<link rel="stylesheet" type="text/css" href="/css/index-2b371326aa93ce4b611853a309b69b29.css">

Spring 會自動讀取資源md5,然后添加到index.css的名字后面,因此當資源內容發生變化的時候,文件名發生變化,就會更新本地資源。

配置方式:

application.properties中做如下配置:

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

這樣配置后,所有/**請求的靜態資源都會被處理為上面例子的樣子。

到這兒還沒完,我們在寫資源url的時候還要特殊處理。

首先增加如下配置:

@ControllerAdvice
public class ControllerConfig {

    @Autowired
    ResourceUrlProvider resourceUrlProvider;

    @ModelAttribute("urls")
    public ResourceUrlProvider urls() {
        return this.resourceUrlProvider;
    }

}

然后在頁面寫的時候用下面的寫法:

<link rel="stylesheet" type="text/css" href="${urls.getForLookupPath('/css/index.css')}">

使用urls.getForLookupPath('/css/index.css')來得到處理后的資源名。

版本號 方式

application.properties中做如下配置:

spring.resources.chain.strategy.fixed.enabled=true
spring.resources.chain.strategy.fixed.paths=/js/**,/v1.0.0/**
spring.resources.chain.strategy.fixed.version=v1.0.0

這里配置需要特別注意,將version的值配置在paths中。原因我們在講Spring MVC 處理邏輯的時候說。

在頁面寫的時候,寫法如下:

<script type="text/javascript" src="${urls.getForLookupPath('/js/index.js')}"></script>

注意,這里仍然使用了urls.getForLookupPathurls配置方式見上一種方式。

在請求的實際頁面中,會顯示為:

<script type="text/javascript" src="/v1.0.0/js/index.js"></script>

可以看到這里的地址是/v1.0.0/js/index.js

靜態資源版本管理 處理過程

在Freemarker模板首先會調用urls.getForLookupPath方法,返回一個/v1.0.0/js/index.js/css/index-2b371326aa93ce4b611853a309b69b29.css

這時頁面上的內容就是處理后的資源地址。

這之后瀏覽器發起請求。

這里分開說。

第一種md5方式

請求/css/index-2b371326aa93ce4b611853a309b69b29.css,我們md5配置的paths=/**,所以Spring MVC 會嘗試url中是否包含-,如果包含會去掉后面這部分,然后去映射的目錄(如/static/)查找/css/index.css文件,如果能找到就返回。

第二種版本方式

請求/v1.0.0/js/index.js

如果我們paths中沒有配置/v1.0.0,那么上面這個請求地址就不會按版本方式來處理,因此會找不到上面的資源。

如果配置了/v1.0.0,Spring 就會將/v1.0.0去掉再去找/js/index.js,最終會在/static/下面找到。

下面是模版的配置,引用使用Spring Boot開發WEB頁面

mvc

spring.mvc.async.request-timeout
設定async請求的超時時間,以毫秒為單位,如果沒有設置的話,以具體實現的超時時間為準,比如tomcat的servlet3的話是10秒.
spring.mvc.date-format
設定日期的格式,比如dd/MM/yyyy.
spring.mvc.favicon.enabled
是否支持favicon.ico,默認為: true
spring.mvc.ignore-default-model-on-redirect
在重定向時是否忽略默認model的內容,默認為true
spring.mvc.locale
指定使用的Locale.
spring.mvc.message-codes-resolver-format
指定message codes的格式化策略(PREFIX_ERROR_CODE,POSTFIX_ERROR_CODE).

view

spring.view.prefix
設定mvc視圖的前綴.
spring.view.suffix
設定mvc視圖的后綴.

resource

spring.resources.add-mappings
是否開啟默認的資源處理,默認為true
spring.resources.cache-period
設定資源的緩存時效,以秒為單位.
spring.resources.chain.cache
是否開啟緩存,默認為: true
spring.resources.chain.enabled
是否開啟資源 handling chain,默認為false
spring.resources.chain.html-application-cache
是否開啟h5應用的cache manifest重寫,默認為: false
spring.resources.chain.strategy.content.enabled
是否開啟內容版本策略,默認為false
spring.resources.chain.strategy.content.paths
指定要應用的版本的路徑,多個以逗號分隔,默認為:[/**]
spring.resources.chain.strategy.fixed.enabled
是否開啟固定的版本策略,默認為false
spring.resources.chain.strategy.fixed.paths
指定要應用版本策略的路徑,多個以逗號分隔
spring.resources.chain.strategy.fixed.version
指定版本策略使用的版本號
spring.resources.static-locations
指定靜態資源路徑,默認為classpath:[/META-INF/resources/,/resources/, /static/, /public/]以及context:/

freemarker

spring.freemarker.allow-request-override
指定HttpServletRequest的屬性是否可以覆蓋controller的model的同名項
spring.freemarker.allow-session-override
指定HttpSession的屬性是否可以覆蓋controller的model的同名項
spring.freemarker.cache
是否開啟template caching.
spring.freemarker.charset
設定Template的編碼.
spring.freemarker.check-template-location
是否檢查templates路徑是否存在.
spring.freemarker.content-type
設定Content-Type.
spring.freemarker.enabled
是否允許mvc使用freemarker.
spring.freemarker.expose-request-attributes
設定所有request的屬性在merge到模板的時候,是否要都添加到model中.
spring.freemarker.expose-session-attributes
設定所有HttpSession的屬性在merge到模板的時候,是否要都添加到model中.
spring.freemarker.expose-spring-macro-helpers
設定是否以springMacroRequestContext的形式暴露RequestContext給Spring’s macro library使用
spring.freemarker.prefer-file-system-access
是否優先從文件系統加載template,以支持熱加載,默認為true
spring.freemarker.prefix
設定freemarker模板的前綴.
spring.freemarker.request-context-attribute
指定RequestContext屬性的名.
spring.freemarker.settings
設定FreeMarker keys.
spring.freemarker.suffix
設定模板的后綴.
spring.freemarker.template-loader-path
設定模板的加載路徑,多個以逗號分隔,默認: ["classpath:/templates/"]
spring.freemarker.view-names
指定使用模板的視圖列表.

velocity

spring.velocity.allow-request-override
指定HttpServletRequest的屬性是否可以覆蓋controller的model的同名項
spring.velocity.allow-session-override
指定HttpSession的屬性是否可以覆蓋controller的model的同名項
spring.velocity.cache
是否開啟模板緩存
spring.velocity.charset
設定模板編碼
spring.velocity.check-template-location
是否檢查模板路徑是否存在.
spring.velocity.content-type
設定ContentType的值
spring.velocity.date-tool-attribute
設定暴露給velocity上下文使用的DateTool的名
spring.velocity.enabled
設定是否允許mvc使用velocity
spring.velocity.expose-request-attributes
是否在merge模板的時候,將request屬性都添加到model中
spring.velocity.expose-session-attributes
是否在merge模板的時候,將HttpSession屬性都添加到model中
spring.velocity.expose-spring-macro-helpers
設定是否以springMacroRequestContext的名來暴露RequestContext給Spring’s macro類庫使用
spring.velocity.number-tool-attribute
設定暴露給velocity上下文的NumberTool的名
spring.velocity.prefer-file-system-access
是否優先從文件系統加載模板以支持熱加載,默認為true
spring.velocity.prefix
設定velocity模板的前綴.
spring.velocity.properties
設置velocity的額外屬性.
spring.velocity.request-context-attribute
設定RequestContext attribute的名.
spring.velocity.resource-loader-path
設定模板路徑,默認為: classpath:/templates/
spring.velocity.suffix
設定velocity模板的后綴.
spring.velocity.toolbox-config-location
設定Velocity Toolbox配置文件的路徑,比如 /WEB-INF/toolbox.xml.
spring.velocity.view-names
設定需要解析的視圖名稱.

thymeleaf

spring.thymeleaf.cache
是否開啟模板緩存,默認true
spring.thymeleaf.check-template-location
是否檢查模板路徑是否存在,默認true
spring.thymeleaf.content-type
指定Content-Type,默認為: text/html
spring.thymeleaf.enabled
是否允許MVC使用Thymeleaf,默認為: true
spring.thymeleaf.encoding
指定模板的編碼,默認為: UTF-8
spring.thymeleaf.excluded-view-names
指定不使用模板的視圖名稱,多個以逗號分隔.
spring.thymeleaf.mode
指定模板的模式,具體查看StandardTemplateModeHandlers,默認為: HTML5
spring.thymeleaf.prefix
指定模板的前綴,默認為:classpath:/templates/
spring.thymeleaf.suffix
指定模板的后綴,默認為:.html
spring.thymeleaf.template-resolver-order
指定模板的解析順序,默認為第一個.
spring.thymeleaf.view-names
指定使用模板的視圖名,多個以逗號分隔.

groovy模板

spring.groovy.template.allow-request-override
指定HttpServletRequest的屬性是否可以覆蓋controller的model的同名項
spring.groovy.template.allow-session-override
指定HttpSession的屬性是否可以覆蓋controller的model的同名項
spring.groovy.template.cache
是否開啟模板緩存.
spring.groovy.template.charset
指定Template編碼.
spring.groovy.template.check-template-location
是否檢查模板的路徑是否存在.
spring.groovy.template.configuration.auto-escape
是否在渲染模板時自動排查model的變量,默認為: false
spring.groovy.template.configuration.auto-indent
是否在渲染模板時自動縮進,默認為false
spring.groovy.template.configuration.auto-indent-string
如果自動縮進啟用的話,是使用SPACES還是TAB,默認為: SPACES
spring.groovy.template.configuration.auto-new-line
渲染模板時是否要輸出換行,默認為false
spring.groovy.template.configuration.base-template-class
指定template base class.
spring.groovy.template.configuration.cache-templates
是否要緩存模板,默認為true
spring.groovy.template.configuration.declaration-encoding
在寫入declaration header時使用的編碼
spring.groovy.template.configuration.expand-empty-elements
是使用
這種形式,還是
</br>這種展開模式,默認為: false)
spring.groovy.template.configuration.locale
指定template locale.
spring.groovy.template.configuration.new-line-string
當啟用自動換行時,換行的輸出,默認為系統的line.separator屬性的值
spring.groovy.template.configuration.resource-loader-path
指定groovy的模板路徑,默認為classpath:/templates/
spring.groovy.template.configuration.use-double-quotes
指定屬性要使用雙引號還是單引號,默認為false
spring.groovy.template.content-type
指定Content-Type.
spring.groovy.template.enabled
是否開啟groovy模板的支持.
spring.groovy.template.expose-request-attributes
設定所有request的屬性在merge到模板的時候,是否要都添加到model中.
spring.groovy.template.expose-session-attributes
設定所有request的屬性在merge到模板的時候,是否要都添加到model中.
spring.groovy.template.expose-spring-macro-helpers
設定是否以springMacroRequestContext的形式暴露RequestContext給Spring’s macro library使用
spring.groovy.template.prefix
指定模板的前綴.
spring.groovy.template.request-context-attribute
指定RequestContext屬性的名.
spring.groovy.template.resource-loader-path
指定模板的路徑,默認為: classpath:/templates/
spring.groovy.template.suffix
指定模板的后綴
spring.groovy.template.view-names
指定要使用模板的視圖名稱.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,197評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,415評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,104評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,884評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,647評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,130評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,208評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,366評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,887評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,737評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,939評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,478評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,174評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,586評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,827評論 1 283
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,608評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,914評論 2 372

推薦閱讀更多精彩內容