springboot静态页面、动态页面及WebMvcConfigurer使用分析

1、绝对路径写死不合理,相对路径问题待思考?
2、在SpringBoot项目中,默认访问 _static_目录下的静态文件,如果自定义怎么处理,原理分析?
目录结构如下图:
在这里插入图片描述
静态页面静态页面与动态页面学习

Spring Boot 默认为我们提供了静态资源处理,默认提供的静态资源映射如下:

	 - classpath:/META-INF/resources
	 - classpath:/resources
	 - classpath:/static
	 - classpath:/public

这些目录的静态资源可以直接以:http://localhost:8888/XXX.html 的形式访问到,如下图:
在这里插入图片描述
如果有层级关系如下图直接访问:
在这里插入图片描述
在这里插入图片描述

或者从后台跳转到静态static-index.html,代码如下:
在这里插入图片描述
在这里插入图片描述

优先级顺序为:META-INF/resources > resources > static > public
在这里插入图片描述
动态页面
动态页面需要先请求服务器,访问后台应用程序,处理数据,然后再转向到页面,比如访问JSP。spring boot建议不要使用JSP,默认使用Thymeleaf来做动态页面。
在这里插入图片描述
测试代码如下:
在这里插入图片描述
在这里插入图片描述
问题及结论
1、jar包相互覆盖,导致错误判断
静态页面的return默认是跳转到/static/index.html,引入了thymeleaf组件,动态跳转会覆盖默认的静态跳转,默认就会跳转到/templates/index.html,注意看两者return代码也有区别,动态没有html后缀。
2、thymeleaf组件默认跳转的templates目录可以更改吗?答案是可以更改的,我们只需这样配置即可:
在这里插入图片描述
但是查看原码可知thymeleaf组件只支持单目录,多目录不支持

3、相对路径问题和自定义问题

测试结果为:如果使用了 WebMvcConfigurer,则自动配置类 WebMvcAutoConfiguration 会失效,因此默认映射路径 /static, /public, META-INF/resources, /resources 都将失效
但官方给的声明说不会失效声明1声明2

If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
As in normal MVC usage, any WebMvcConfigurer beans that you provide can also contribute converters by overriding the configureMessageConverters method. However, unlike with normal MVC, you can supply only additional converters that you need (because Spring Boot uses the same mechanism to contribute its defaults). Finally, if you opt out of the Spring Boot default MVC configuration by providing your own @EnableWebMvc configuration, you can take control completely and do everything manually by using getMessageConverters from WebMvcConfigurationSupport.
See the WebMvcAutoConfiguration source code for more details.

使用WebMvcConfigurer自定义配置规则如下:

  • 无任何前缀 -> “文档根目录”(一般指代 src/main/webapp 目录), 例如
    localhost:8080/index.html 定位至 src/main/webapp/static/index.html
  • 存在前缀 classpath -> 类路径(一般指代 src/main/resources 目录)
  • 存在前缀 file:// -> 文件系统路径(“绝对路径”)
    在这里插入图片描述
    在这里插入图片描述
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值