SpringBoot基礎03:靜態資源和首頁定製
阿新 • • 發佈:2022-03-24
SpringBoot基礎03:靜態資源和首頁定製
靜態資源
- 在SpringBoot中,可以使用一下方式處理靜態資源
-
webjars
http://localhost:8080/webjars/
-
public,static,/**,resources
http://localhost:8080
- 優先順序:resources>static(預設)>public
首頁如何定製
-
匯入模板引擎:在pom.xml中匯入thymeleaf中新增相關啟動器SpringBoot將自動配置相關依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
-
通過原始碼分析,預設在classpath:/templates/下尋找.html檔案,因此在resources目錄下的templates目錄中建立相關.html檔案就可以通過controller來訪問相關頁面了
@ConfigurationProperties(prefix = "spring.thymeleaf") public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html";
-
通過Controller類來傳參,並在html頁面中顯示出來,前端介面獲取後端元素 th:元素名的方式來進行替換
package com.lurenj.controller; import org.springframework.ui.Model; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; //在templates目錄下的所有頁面,只能通過controller來跳轉 //需要模板引擎的支援! thymeleaf @Controller public class IndexController { @RequestMapping("/test") public String test(Model model){ model.addAttribute("msg","springboot"); return "test"; } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--所有的html元素都可以被thymeleaf替換接管: th:元素名--> <h1 th:text="${msg}"></h1> </body> </html>
-
自定義檢視解析器,在主程式同級目錄下建立config資料夾,在其中建立自定義類,通過ViewResolver介面實現自定義試圖解析器,並加入到容器中
package com.lurenj.config; //全面擴充套件 springMVC import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.View; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.Locale; @Configuration public class MyMvcConfig implements WebMvcConfigurer { //public interface ViewResolver 實現了檢視解析器介面的類,我們就可以把它看做檢視解析器
@Bean public ViewResolver myViewResolver(){ return new MyViewResolver(); } //自定義一個自己的檢視解析器MyViewResolver public static class MyViewResolver implements ViewResolver{ @Override public View resolveViewName(String viewName, Locale locale) throws Exception { return null; } }
}
-
擴充套件SpringMvc
package com.lurenj.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; //如果我們要擴充套件springMVC,官方建議的做法如下! @Configuration public class MyMvcConfig implements WebMvcConfigurer { //檢視跳轉 @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/lurenj").setViewName("test"); } }