feat: @RestController使用方式和将视图和模型拆开

This commit is contained in:
Bunny 2025-01-22 18:08:32 +08:00
parent 9a7349d93d
commit 4df0d12992
5 changed files with 52 additions and 0 deletions

View File

@ -95,6 +95,8 @@ public List<String> getJson() {
### 使用`@RestController` ### 使用`@RestController`
#### 使用方式1
如果使用`@RestController`那么返回的就是JSON对象但是这时候要想返回网页文件需要使用`ModelAndView` 如果使用`@RestController`那么返回的就是JSON对象但是这时候要想返回网页文件需要使用`ModelAndView`
```java ```java
@ -126,4 +128,19 @@ public class UseRestController {
<h4 th:text="'消息:'+ ${message}"></h4> <h4 th:text="'消息:'+ ${message}"></h4>
</body> </body>
</html> </html>
```
> 其中`modelAndView.addObject("message", "这是消息内容");`是可选的
#### 使用方式2
在控制器方法上使用`ModelAndView`
```java
@GetMapping("page/test2")
public ModelAndView test2(ModelAndView modelAndView) {
modelAndView.addObject("hello", "你好");
modelAndView.setViewName("page/test2");
return modelAndView;
}
``` ```

View File

@ -1,6 +1,7 @@
package cn.bunny.mvc.controller; package cn.bunny.mvc.controller;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
@ -45,4 +46,11 @@ public class UseController {
return list; return list;
} }
// 将视图和模型拆开
@GetMapping("test3")
public String test3(Model model) {
model.addAttribute("test3", "测试3");
return "page/test3";
}
} }

View File

@ -16,4 +16,11 @@ public class UseRestController {
modelAndView.addObject("message", "这是消息内容"); modelAndView.addObject("message", "这是消息内容");
return modelAndView; return modelAndView;
} }
@GetMapping("page/test2")
public ModelAndView test2(ModelAndView modelAndView) {
modelAndView.addObject("hello", "你好");
modelAndView.setViewName("page/test2");
return modelAndView;
}
} }

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>在控制器方法上使用ModelAndView</title>
</head>
<body>
<h1>在控制器方法上使用ModelAndView</h1>
</body>
</html>

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测试3</title>
</head>
<body>
<h1 th:text="'测试3' + ${test3}"></h1>
</body>
</html>