SpringBoot2.x|Thymeleaf頁面不能正常載入css、js文件


1、實現實現WebMvcConfig配置類可以解決頁面不能加載css,js的問題;

擴展SpringMvc,編寫一個配置類(@Configuration),是WebMvcConfigurationAdapter抽象類類型(WebMvcConfigurer 接口類型的),且不能標注@EnableWebMvc
如果SpringBoot本身的自動配置不能滿足自己的需求,就需要擴展SpringMVC配置文件。WebMvcConfigurer可以擴展SpringMvc的功能。

 1 package com.bie.config;
 2 
 3 import org.springframework.context.annotation.Configuration;
 4 import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
 5 import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
 6 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 7 
 8 /**
 9  *
10  */
11 @Configuration
12 public class SpringMvcWebConfigSupport implements WebMvcConfigurer {
13 
14     /**
15      * 默認訪問的是首頁 //保留了SpringBoot的自動配置,也使用了自己的SpringMmv的配置
16      * @param registry
17      */
18     @Override
19     public void addViewControllers(ViewControllerRegistry registry) {
20         registry.addViewController("/").setViewName("index");//前拼templates,后拼.html
21         registry.addViewController("/index.html").setViewName("index");//瀏覽器發送/請求來到login.html頁面,不用寫controller控制層的請求方法了
22     }
23 
24     /**
25      * 將static下面的js,css文件加載出來
26      * @param registry
27      */
28     @Override
29     public void addResourceHandlers(ResourceHandlerRegistry registry) {
30         //registry.addResourceHandler("/static/").addResourceLocations("classpath:/static/");
31         registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
32     }
33 }

因為在SpringBoot的2.x新版本中WebMvcConfigurerAdapter (使用WebMvcConfigurerAdapter可以來擴展SpringMVC的功能)配置類已經不推薦使用了,可以使用WebMvcConfigurer 或者WebMvcConfigurationSupport來配置自己的配置信息。

 1 //package com.bie.config;
 2 //
 3 //import org.springframework.context.annotation.Configuration;
 4 //import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
 5 //import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 6 //
 7 ///**
 8 // * WebMvcConfigurerAdapter類已經不推薦使用了
 9 // */
10 //@Configuration
11 //public class SpringMvcWebConfig extends WebMvcConfigurerAdapter {
12 //
13 ////    @Override
14 ////    public void addViewControllers(ViewControllerRegistry registry) {
15 ////        //瀏覽器發送請求到到指定的頁面
16 ////        registry.addViewController("/").setViewName("index");
17 ////    }
18 //
19 //    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
20 //        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter(){
21 //            @Override
22 //            public void addViewControllers(ViewControllerRegistry registry) {
23 //                registry.addViewController("/").setViewName("index");
24 //            }
25 //        };
26 //        return adapter;
27 //    }
28 //}

 

待續......


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM