在Spring Boot中訪問靜態頁面有以下幾種方法:
在src/main/resources/static目錄下創建靜態頁面文件,直接通過URL訪問即可。例如,如果有一個名為index.html的靜態頁面文件,可以通過http://localhost:8080/index.html訪問。
在src/main/resources/templates目錄下創建Thymeleaf模板文件,可以使用Thymeleaf模板引擎渲染頁面,然后返回給瀏覽器。這種方式可以將動態數據傳遞給頁面進行渲染。例如,如果有一個名為index.html的Thymeleaf模板文件,可以通過創建一個Controller來返回該頁面:
@Controller
public class MyController {
@GetMapping("/index")
public String getIndexPage() {
return "index";
}
}
然后通過http://localhost:8080/index來訪問。
@Controller注解和@RequestMapping注解創建一個Controller,在方法中使用ModelAndView類來設置要返回的頁面和數據。例如:@Controller
public class MyController {
@RequestMapping("/")
public ModelAndView home() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
return modelAndView;
}
}
然后通過http://localhost:8080/來訪問。
需要注意的是,以上方法中的index表示頁面的名稱,對應的是文件名(不含后綴)。如果Spring Boot使用的是默認的Thymeleaf模板引擎,頁面文件的后綴應為.html;如果使用的是其他模板引擎,如FreeMarker或Velocity,相應地修改文件后綴名。