springboot+thymeleaf找不到視圖的解決方案
情況:
springboot + thymeleaf打成jar包后,報錯,但在eclipse本地跑卻可以:
template might not exist or might not be accessible by any of the configured Template Resolvers
yml配置:
spring: thymeleaf: cache: false #開發時關閉緩存,不然沒法看到實時頁面 mode: HTML5 # 用非嚴格的 HTML #enabled: true encoding: UTF-8 prefix: classpath:/templates/ suffix: .html servlet: content-type: text/html
controller返回視圖:
@RequestMapping('demo')public String demo(Model model) { //return '/demo';//這種是有問題的 return 'demo';}
解釋:
這里其實是由于我們的yml配置中,已經配置了/templates/,因此如果返回/demo的話,那就會找不到,因為映射視圖變成了://demo,所以,這里最好去掉其中一個“/”;
不然打成jar包后,會找不到,這個要作為項目的規范,不然后面發布正式時,太多也不好修改;如果有更好的辦法也請告訴我一聲,謝謝。
springboot 使用thymeleaf模板遇到的一些問題使用springboot+thymeleaf遇到一些問題,主要歸為如下幾點:
1.在/templates目錄下創建自定義目錄/my,并在該目錄下創建index.html,程序中如何訪問index.html
2.如果不使用/templates目錄作為默認路徑,該如何配置
問題1解決方式:
在controller層方法中通過設置ModelAndView名稱的為:my/index,然后返回該ModelAndView,然后該接口方法時就會跳轉到index.html
示例代碼如下:
@RequestMapping(value='getIndex')public ModelAndView getIndex(ModelAndView model)throws Exception{ //訪問自定義目錄下/templates/my/index.html,要注意路徑格式 model.setViewName('my/index'); return model;}問題2
解決方式:
在application.properties配置文件中通過spring.thymeleaf.prefix屬性進行設置,例如設置默認路徑為/templates/my
示例代碼如下:
spring.thymeleaf.prefix=classpath:/templates/my
springboot+thymeleaf使用的代碼如下:
https://github.com/ingorewho/springboot-develope/tree/master/springboot-thymeleaf
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: