如果用springMVC开发web应用,我们需要导入web支持.在webapp中添加网页,资源等等,但是在springBoot中,并没有webapp,也没有首页,这是应该怎么开发呢
首先我们都知道,springboot的最大特点就是四个字自动装配
.
使用springboot的一些步骤:
- 创建应用,选择模块.导入对应的Start启动器
- 配置文件,替换原有的操作.
- 编写业务代码
再谈谈自动装配,我们需要知道springboot到底帮我们配置了什么?我们能不能进行修改?能修改哪些东西,能不能扩展呢?
我们知道
- springboot底层有大量的XXXAutoConfiguration向容器中自动配置组件
- xxxxProperties:自动配置类,装配配置文件中自定义的一些内容
从springMvc过渡到springboot Web开发
要解决的问题: - 导入静态资源,…
- 首页
- jsp,模板引擎Thymeleaf
- 装配扩展SpringMVC
- 增删改查
- 拦截器
- 国际化(实现中英文切换的问题)
1.静态资源
第一步:我们在idea中创建一个spring initializr.选择springweb.等待idea创建好之后删除多余文件如:
第二步:在com.qiu创建一个controller文件夹添加一个类,这一步我们要保证tomcat能正常使用
package com.qiu.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello,world";
}
}
然后在启动Springboot03WebApplication.保证网页上能正常显示helloworld
这样就算启动成功了
回到正题:静态资源如何导入?
分析源码:
双击shift,搜索webMvcAutoConfiguration这个类:
找到这么一段代码:
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
}
首先判断如果静态资源的东西已经被自定义了,那么就返回一个话Default resource handling disabled,有自定义配置,则默认失效
关于如果自定义,我们需要从源码中找到WebMvcProperties这个类,查看里面关于自定义了哪些方法,进而在application.yaml中进行相应的配置.
接着往下:看到一个webjars:
什么是webjars?
web Libraries in jars
网址:https://www.webjars.org/
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.5.1</version>
</dependency>
引入webjars就能把jquery给导进来了
这是通过webjars引入.
第二种方式:获得静态资源的路径
在深入源码查看:
/**
当前目录都能识别
再找发现
以上四个位置都支持静态资源的导入
这四个位置都能放静态资源.
而且:这三个是有优先级的
resource>static>public
注意:
如果自定义在配置文件中设置静态资源的存放位置,则默认的存放位置就失效了,一般不建议这么干
静态资源最终总结: