温馨提示×

springboot怎么访问静态页面

小亿
317
2023-11-01 15:42:03
栏目: 编程语言

在Spring Boot中访问静态页面有以下几种方法:

  1. src/main/resources/static目录下创建静态页面文件,直接通过URL访问即可。例如,如果有一个名为index.html的静态页面文件,可以通过http://localhost:8080/index.html访问。

  2. 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来访问。

  1. 使用@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,相应地修改文件后缀名。

0