spring学习笔记3|从源码看静态资源加载
使用springmvc开发时,jsp文件是写在webapp下的,而springboot的工程结构是没有这个目录的,没有index.jsp作为首页,更没有web.xml来让我们手动配置dispatcherServlet和编码过滤器等,那么静态资源写在哪里?如何访问?优先级是什么?springboot经常更新,从源码角度理解问题,可以减少多余动作,也是提高java水平的方法。
【静态资源访问】
搜索WebMvcAutoConfiguration类下,addResourceHandlers方法指明的静态资源的来源(方法的重载)
1.web jars:先上webjars导入,再用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/"
它们的访问优先级?
classpath:/resources/
classpath:/static/(默认)
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。
导入一个模板引擎依赖thymeleaf,作用和jsp一样。从maven找一个spring-boot-starter-thymeleaf就行,导入后就可以找到ThymeleafProperties类,里面注明了:
String DEFAULT_PREFIX = "classpath:/templates/";
String DEFAULT_SUFFIX = ".html";
说明只要将html放在classpath:/templates/下就可以在由@Controller注释的类下被访问了。(注意@RequestController访问不到)