【SpringBoot】返回参数-返回页面

时间:2024-04-16 14:13:43

首先在 static 文件夹中创建 index.html 文件:
在这里插入图片描述
代码:

<html>
<body>
    <h1>hello word!!!</h1>
    <p>this is a html page</p>
</body>
</html>

可以直接使用地址访问(确保 index.html 文件在 static 文件夹中):
在这里插入图片描述

也可以后端返回 index.html:

@RequestMapping("/return")
@Controller
public class ReturnController {
    // 返回 html页面
    @RequestMapping("/r1")
    public String r1() {
        return "/index.html";
    }
}

在这里插入图片描述

早期,后端会返回前端视图,所以使用 @Controller 注解,而现在大多是前后端分离,只需要给前端返回数据即可,因此使用 @RestController 注解。而 @RestController 相当于 @Controller + @ResponseBody,所以如下两种方式等价:
在这里插入图片描述