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>

  

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

 

 

 

猜你喜欢

转载自www.cnblogs.com/forwrader/p/10541699.html