一、在pom.xml文件中导入SpringBoot web启动的starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
二、SpringBoot中引入静态资源
1.SpringBoot以 webjars jar包的方式引入静态资源
webjars 官网:https://www.webjars.com/ 我们可以在官网中找到对应的静态资源依赖,配置到pom.xml中 如图:
2. 从浏览器中直接访问项目的静态资源,如访问jquery
SpringBoot项目 在浏览器中输入 /webjars/** 路径,默认会去 classpath:/META-INF/resources/webjars/**找资源
在项目中导入jquery的依赖后jar包中会有如下路径:
访问jquery的路径为: http://localhost:8080/webjars/jquery/3.4.1/jquery.js
3.SpringBoot中引入我们自己的js、css等
SpringBoot默认的静态资源的文件夹(默认不拦截)。静态资源文件夹下的内容可以从浏览器中直接访问
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":
4.SpringBoot项目的欢迎页设置
欢迎页 : 静态资源文件夹下的所有index.html页面。
5.SpringBoot项目 访问时的图标设置
访问时地址前带的图标:静态资源文件夹下的/favicon.ico
6.修改SpringBoot默认的静态资源文件夹
可以在application.properties文件中通过spring.resources.static-locations= 设置
例:spring.resources.static-locations=classpath:/mystaticfile
三、引入thymeleaf模板引擎
1.在pom.xml中引入thymeleaf的starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.在application.properties中设置thymeleaf的缓存禁用
spring.thymeleaf.cache=false
在开发中如果想让修改后的html页面生效,需要在idea中 按 ctrl+f9 让idea重新编译一下该页面。
3.如果想改变SpringBoot 自己默认的thymeleaf的版本号。
在pom.xml的<properties></properties>标签中设置thymeleaf版本号,以覆盖SpringBoot版本控制的版本号
例:<properties>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
</properties>
4.让页面具有thymeleaf渲染的功能
thymeleaf默认的前缀:classpath:/templates/
thymeleaf默认的后缀:.html
只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
5.要在html页面中导入thymeleaf的名称空间。以便在html中获取thymeleaf的语法提示
<html lang="en" xmlns:th="http://www.thymeleaf.org">
例:
四、SpringBoot自动注入springmvc
1.SpringBoot为我们自动注入了视图解析器(ViewResolver)
如果我们想手动配置ViewResolver,第一步:只需要手动写一个类实现ViewResolver接口,并重写resolveViewName方法。用@Configuration注解让改类在项目启动的时候就被加载
第二步:再将该类用@Bean方式注入到spring容器中
但是我们一般也不这么做,默认使用SpringBoot自带的就行。
2.SpringBoot为我们自动注入了类型转换器(Converter)
3.SpringBoot为我们自动注入了日期格式化器(formatter),
4.SpringBoot为我们自动注入了消息转换器。HttpMessageConverter 用来 springmvc转换http请求和响应的
例如:user——>json
SpringBoot为我们自动配置了很多组件,但是在使用的时候,SpringBoot会先看用户是否自己配置了组件,如果用户自己配置了
就用用户自己配置的,如果没有就用默认配置的。
五、扩展SpringMVC。用@Configuration注解创建一个配置类,并且继承WebMvcConfigurerAdapter 实现对应的方法
例:在页面中请求/atguigu就能够映射到success页面。 这样就不需要在controller中写一个方法再用@RequestMapping来映射了。但这样写的一个缺点是不能携带参数。
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送 /atguigu 请求来到 success
registry.addViewController("/atguigu").setViewName("success");
}
}