Spriongboot創建的項目,在resources -> templates下的資源是不能直接訪問的,沒有開放訪問權限。這是因為templates文件夾,是放置模板文件的,因此需要視圖解析器來解析它。所以必須通過服務器內部進行訪問,也就是要走控制器 -> 服務 -> 視圖解析器這個流程才行。同時,存在安全問題。比如說,你把你后台的html文件放到templates,而這個文件夾對外又是開放的,就會存在安全隱患。
- 這里提供兩種可以方式訪問templates模板下的資源文件
- 方式一:在application.yml或者application.properties配置文件中將訪問權限開放(這種方式不推薦)
spring: resources: static-locations: classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/, classpath:/templates/
或者
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/templates/
- 方式二:通過內部controller跳轉訪問的資源
比如要訪問templates下的test.html。先請求內部控制器,由控制器跳轉test.html頁面
1 @Controller 2 public class Test { 3 4 @GetMapping("/test") 5 public String test() { 6 return "test"; 7 } 8 }