SpringBoot——web开发之静态资源引入

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/rubulai/article/details/82718388

1、虽说SpringBoot为我们提供了很多可以放置静态资源的文件夹,但静态页面(html)最好放在templates文件夹下,因为放在该文件夹下才能得到模板引擎的解析,放在其他静态资源文件夹下则不能得到模板引擎的解析,这样就无法使用模板引擎的强大功能了

2、假如在public和templates文件夹下都存在index.html,那么在不进行其他设置的情况下默认首页是public文件夹下的index.html,而不是templates下的index.html,如果想使默认首页变为templates下的则可以使用以下方式进行映射:

①在Controller中写处理请求"/"的方法,在方法中返回资源的位置(模板引擎默认会到templates文件夹下找资源)

@Controller
public class TestController {

    @RequestMapping({"/","/index.html"})
    public String index(){
        return "index";
    }
}

②在我们自定义的WebMvcConfigurerAdapter中添加viewController:

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index.html").setViewName("index");
    }
}

③在我们自定义的WebMvcConfigurerAdapter中注册一个返回WebMvcConfigurerAdapter类型对象的Bean,在该Bean中添加请求映射:

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        //因为WebMvcConfigurerAdapter是抽象类,需要在方法体中实现其抽象方法,虽然该类没有抽象方法,但方法体不可省
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter(){
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("index");
                registry.addViewController("/index.html").setViewName("index");
            }
        };
        return adapter;
    }
}

原理很简单,SpringBoot会将所有标注为@Configuration的类当做容器配置类,在该类中使用@Bean注解就相当于向容器中添加了一个WebMvcConfigurationAdapter组件,而在SpringBoot为SpringMVC提供的自动配置中会将容器中所有的WebMvcConfigurationAdapter进行组合,使它们一起起作用

3、公共资源使用webjars的方式引用

①导入bootstrap的webjars:

<!-- bootstrap的webjar-->
<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>bootstrap</artifactId>
	<version>4.1.3</version>
</dependency>

②引入模板引擎的命名空间,会给我们代码提示:

<html lang="en" xmlns:th="http://www.thymeleaf.org">

③使用th:xxx属性引入webjars资源,具体路径需要看该资源在依赖包中的位置,比如:

<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.1.3/css/bootstrap.css}" rel="stylesheet">

④非webjars资源我们也可以使用th:xxx属性引入,这样有一个好处,就是资源的地址会随着项目名的改变而动态改变:

<link th:href="@{/asserts/css/signin.css}" href="asserts/css/signin.css" rel="stylesheet">

猜你喜欢

转载自blog.csdn.net/rubulai/article/details/82718388
今日推荐