1. 程式人生 > 程式設計 >Spring boot 路徑對映的實現

Spring boot 路徑對映的實現

這篇文章主要介紹了spring boot 路徑對映的實現,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

在spring boot中整合thymeleaf後,我們知道thymeleaf的預設的html的路徑為classpath:/templates也就是resources/templates,那如何訪問這個路徑下面的靜態頁面呢?假設我們要訪問一個頁面為hello.html。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h1>hell spring boot!!</h1>
</body>
</html>

該頁面位於templates下,當然也可以在application.properties檔案中修改預設路徑。

spring.thymeleaf.prefix=classpath:/templates

1.使用controller中的方法直接返回該頁面

@Controller
public class HelloController {
  @GetMapping("/hello")
  public String hello(){
  //在整合thymeleaf後 會在預設路徑下尋找名字為hello的html頁面
    return "hello";
  }
}

2.實現WebMvcConfigure介面中的addViewControllers方法進行路徑的對映

@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
  @Override
  public void addViewControllers(ViewControllerRegistry registry) {
    //第一個路徑為類似於Controller中的介面的路徑 第二個view為要訪問的頁面
    //實現不需要進行資料渲染的頁面的路徑對映 當然這些頁面沒有在預設的五個靜態頁面訪問路徑下
    registry.addViewController("/hopec").setViewName("hello");    //如果需要新增多個頁面直接在下面繼續新增即可
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。