spring學(xué)習(xí)筆記3|從源碼看靜態(tài)資源加載
使用springmvc開發(fā)時,jsp文件是寫在webapp下的,而springboot的工程結(jié)構(gòu)是沒有這個目錄的,沒有index.jsp作為首頁,更沒有web.xml來讓我們手動配置dispatcherServlet和編碼過濾器等,那么靜態(tài)資源寫在哪里?如何訪問?優(yōu)先級是什么?springboot經(jīng)常更新,從源碼角度理解問題,可以減少多余動作,也是提高java水平的方法。
【靜態(tài)資源訪問】
搜索WebMvcAutoConfiguration類下,addResourceHandlers方法指明的靜態(tài)資源的來源(方法的重載)
1.web jars:先上webjars導(dǎo)入,再用localhost:8080/webjars/jar包路徑訪問
this.mvcProperties.getWebjarsPathPattern()
2./**:localhost:8080/后面接所有路徑均可訪問。
this.mvcProperties.getStaticPathPattern()
/**包括什么?
WebMvcAutoConfiguration類下,WebMvcAutoConfigurationAdapter方法中,webProperties.getResources()指明了CLASSPATH_RESOURCE_LOCATIONS
:
"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"
它們的訪問優(yōu)先級?
classpath:/resources/
classpath:/static/(默認(rèn))
classpath:/public/
3.自定義:在qpplication.properties里定義spring.mvc.static-path-pattern=/changting/**
?if (!this.resourceProperties.isAddMappings()) {
? ? logger.debug("Default resource handling disabled");
【首頁】
搜索WebMvcAutoConfiguration類下,getIndexHtml方法用重載給出兩種途徑
this.getIndexHtml(this.resourceLoader.getResource(location));
和
Resource resource = location.createRelative("index.html"):在classpath下的包里自己寫一個index.html
【模板引擎】
問題:jar 包用于打包類,而war 是一個可以直接運行的 web 模塊。springboot中不再使用war包,不支持jsp。
導(dǎo)入一個模板引擎依賴thymeleaf,作用和jsp一樣。從maven找一個spring-boot-starter-thymeleaf就行,導(dǎo)入后就可以找到ThymeleafProperties類,里面注明了:
String DEFAULT_PREFIX = "classpath:/templates/";
String DEFAULT_SUFFIX = ".html";
說明只要將html放在classpath:/templates/下就可以在由@Controller注釋的類下被訪問了。(注意@RequestController訪問不到)