springboot templates目錄下的頁面文件訪問不到 static 目錄下的 jq 文件


  springboot項目結構中,頁面(eg:.ftl )放在 templates 目錄下,靜態文件 (eg : .js) 放在 static 目錄下, 但是實際操作中發現 controller 訪問到 ftl頁面后, 找不到引用 static 目錄中的 jq 文件

  然后開始了尷尬的一個早上。。。

  

  如果你遇到了這個問題,你首先要想到要把 springboot 中訪問靜態資源的路徑映射到 static 目錄下, 對資源訪問做一個映射,然后去百度吧。。。

  在 application.properties 文件中加入以下資源映射:

  

  貼上項目結構,讓一起入門的小伙伴們看下結構,心理會踏實點 (我的目的就是要在 index.ftl 文件中訪問到 static/js 目錄下的jq文件):

  

 

  其實好像添加上這個配置后就行了的。。。

  你可以通過繼承 WebMvcConfigurerAdapter (這個類已經顯示 deprecated, 但是沒找到替代的新類 ), 實現  addResourceHandlers 方法添加對靜態資源訪問的路徑

  

  如果你只是要引用jquery文件的話,可以通過 webjars 的形式, 在pom文件中 添加依賴

 1 <dependency>
 2     <groupId>org.webjars</groupId>
 3     <artifactId>webjars-locator-core</artifactId>
 4 </dependency>
 5 <dependency>
 6     <groupId>org.webjars</groupId>
 7     <artifactId>bootstrap</artifactId>
 8     <version>3.3.7</version>
 9 </dependency>
10 <dependency>
11     <groupId>org.webjars</groupId>
12     <artifactId>jquery</artifactId>
13     <version>3.1.1</version>
14 </dependency>

  然后直接在 ftl 頁面中加入對所需文件的引用:

  

  *************** 需要注意的點 : 添加webjars, 需要在 addResourcesHandlers 方法中, 把 /resources 目錄加上去 (這個導入jq文件后,看下jq文件的實際目錄就知道了)

   最后加上springboot 整合 ftl 的配置:

spring.mvc.static-path-pattern=/static/** spring.resources.static-locations=classpath:/static/ spring.freemarker.allow-request-override=false #Enable template caching.啟用模板緩存。 spring.freemarker.cache=false spring.freemarker.check-template-location=true spring.freemarker.charset=UTF-8 spring.freemarker.content-type=text/html spring.freemarker.expose-request-attributes=false spring.freemarker.expose-session-attributes=false spring.freemarker.expose-spring-macro-helpers=false #spring.freemarker.prefix= #spring.freemarker.request-context-attribute= #spring.freemarker.settings.*= #設置面板后綴 spring.freemarker.suffix=.ftl

  最后一個 freemarker.suffix 設置看訪問的頁面后綴了,這里是 ftl 就設置成 ftl, 否則訪問不到

   整合 freemarker , pom文件中加上

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

  

  今天遇到了一個小坑,是我太菜,弄了一個早上。。。

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM