springboot怎么访问静态页面

   2025-02-15 2970
核心提示:在Spring Boot中访问静态页面有以下几种方法:在src/main/resources/static目录下创建静态页面文件,直接通过URL访问即可。例如

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

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

src/main/resources/templates目录下创建Thymeleaf模板文件,可以使用Thymeleaf模板引擎渲染页面,然后返回给浏览器。这种方式可以将动态数据传递给页面进行渲染。例如,如果有一个名为index.html的Thymeleaf模板文件,可以通过创建一个Controller来返回该页面:

@Controllerpublic class MyController {    @GetMapping("/index")    public String getIndexPage() {        return "index";    }}

然后通过http://localhost:8080/index来访问。

使用@Controller注解和@RequestMapping注解创建一个Controller,在方法中使用ModelAndView类来设置要返回的页面和数据。例如:
@Controllerpublic 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,相应地修改文件后缀名。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言