例如: 访问localhost:8080/abc时,如果没人处理,那么默认就去这些存在的静态资源文件夹中寻找对应资源
localhost:8080/ 默认找index页面
eg. 我们在public目录下添加一个 favicon.ico ,然后刷新刚才的页面:发现图标发生了变化:
原本是:
变成了:
当然了,我们也可以修改静态资源文件夹的位置: 在application.properties文件中,
通过 spring.resources.static-location=classpath:// 来指定新的位置。
请注意:指定新的静态资源文件夹的位置之后,springboot默认的就不生效了,也就是说我们要通过我们指定的文件夹的位置去访问静态资源,以前的不能访问。
<!--引入Thymeleaf模板引擎启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
如何修改默认设置:
spring:
thymeleaf:
prefix: classpath:/static/
Spring Boot配置静态资源访问,整合Thymeleaf模板 Spring Boot静态资源访问和配置全解析(看不懂你打我)
Thymeleaf 教程 Thymeleaf Tutorial 文档 中文翻译
<html xmlns:th="http://www.thymeleaf.org">
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Index Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<!--前提是我们再通过controller跳转时,往隐含模型中放入了message这个key值-->
<!--在p标签内填入取出来的值,会覆盖掉之前p标签里面的内容-->
<p th:text="${message}">Welcome to BeiJing!</p>
</body>
</html>
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Index Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<!--前提是我们再通过controller跳转时,往隐含模型中放入了message这个key值-->
<!--在p标签内填入取出来的值,会覆盖掉之前p标签里面的内容-->
<p id="p1" th:id="修改id" class="classP1" th:class="修改后的class" th:text="${message}">Welcome to BeiJing!</p>
</body>
</html>
自定义一个自己的解析器然后注册到Bean里面
//如果你想自定义一些定制的功能,只要写这个组件,然后将它交给springboot,springboot就会自动装配
//扩展SpringMVC dispatchservlet
@Configuration //使当前这个类变成配置类
//一但表注了@EnableWebMvc,那么MVC将被全面接管
public class MyMvcConfig implements WebMvcConfigurer {
//public interface ViewResolver 实现了视图解析器接口的类,我们就可以把它看做视图解析器
/*第二步:将自己写的视图解析器注册到Bean里面,它就会自动帮我们装配上*/
@Bean
public ViewResolver MyViewResolver() {
return new MyViewResolver();
}
/*第一步:自定义了一个自己的视图解析器MyViewResolver*/
public static class MyViewResolver implements ViewResolver {
@Override
public View resolveViewName(String s, Locale locale) throws Exception {
return null;
}
}
}
如何看自己的视图解析器是否已经配置成功呢?使用Debug断点测试
ctrl+n 查找到dispatcherServlet
HttpMessageConverters的两个作用加@ResponseBody注解(异步请求),一个是ResponseEntity作为返回值(文件的下载)
除了SpringBoot对SPringMVC的默认配置,如果我们还想要增添一些功能,例如直接跳转到对应页面,拦截器等功能,这就需要扩展SpringMVC了
//使用WebMvcConfigurerAdapter可以来扩展SpringMvc的功能
@Configuration
public class myConfig extends WebMvcConfigurerAdapter
{
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送hello请求,来到hello页面
registry.addViewController("/hello").setViewName("hello");
}
}
//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
//浏览器发送 /hello请求来到 success
registry.addViewController("/hello").setViewName("success");
}
}