springboot+thymeleaf找不到視圖的解決方案
情況:
springboot + thymeleaf打成jar包后,報(bào)錯(cuò),但在eclipse本地跑卻可以:
template might not exist or might not be accessible by any of the configured Template Resolvers
yml配置:
spring: thymeleaf: cache: false #開發(fā)時(shí)關(guān)閉緩存,不然沒法看到實(shí)時(shí)頁面 mode: HTML5 # 用非嚴(yán)格的 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';}
解釋:
這里其實(shí)是由于我們的yml配置中,已經(jīng)配置了/templates/,因此如果返回/demo的話,那就會(huì)找不到,因?yàn)橛成湟晥D變成了://demo,所以,這里最好去掉其中一個(gè)“/”;
不然打成jar包后,會(huì)找不到,這個(gè)要作為項(xiàng)目的規(guī)范,不然后面發(fā)布正式時(shí),太多也不好修改;如果有更好的辦法也請(qǐng)告訴我一聲,謝謝。
springboot 使用thymeleaf模板遇到的一些問題使用springboot+thymeleaf遇到一些問題,主要?dú)w為如下幾點(diǎn):
1.在/templates目錄下創(chuàng)建自定義目錄/my,并在該目錄下創(chuàng)建index.html,程序中如何訪問index.html
2.如果不使用/templates目錄作為默認(rèn)路徑,該如何配置
問題1解決方式:
在controller層方法中通過設(shè)置ModelAndView名稱的為:my/index,然后返回該ModelAndView,然后該接口方法時(shí)就會(huì)跳轉(zhuǎn)到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屬性進(jìn)行設(shè)置,例如設(shè)置默認(rèn)路徑為/templates/my
示例代碼如下:
spring.thymeleaf.prefix=classpath:/templates/my
springboot+thymeleaf使用的代碼如下:
https://github.com/ingorewho/springboot-develope/tree/master/springboot-thymeleaf
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
