diff --git a/mvc/SpringMVC笔记.md b/mvc/SpringMVC笔记.md index 8c1fed0..8b85f90 100644 --- a/mvc/SpringMVC笔记.md +++ b/mvc/SpringMVC笔记.md @@ -95,6 +95,8 @@ public List getJson() { ### 使用`@RestController` +#### 使用方式1 + 如果使用`@RestController`那么返回的就是JSON对象,但是这时候要想返回网页文件,需要使用`ModelAndView` ```java @@ -126,4 +128,19 @@ public class UseRestController {

+``` + +> 其中`modelAndView.addObject("message", "这是消息内容");`是可选的 + +#### 使用方式2 + +在控制器方法上使用`ModelAndView` + +```java +@GetMapping("page/test2") +public ModelAndView test2(ModelAndView modelAndView) { + modelAndView.addObject("hello", "你好"); + modelAndView.setViewName("page/test2"); + return modelAndView; +} ``` \ No newline at end of file diff --git a/mvc/src/main/java/cn/bunny/mvc/controller/UseController.java b/mvc/src/main/java/cn/bunny/mvc/controller/UseController.java index 8347632..36cd655 100644 --- a/mvc/src/main/java/cn/bunny/mvc/controller/UseController.java +++ b/mvc/src/main/java/cn/bunny/mvc/controller/UseController.java @@ -1,6 +1,7 @@ package cn.bunny.mvc.controller; import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -45,4 +46,11 @@ public class UseController { return list; } + + // 将视图和模型拆开 + @GetMapping("test3") + public String test3(Model model) { + model.addAttribute("test3", "测试3"); + return "page/test3"; + } } diff --git a/mvc/src/main/java/cn/bunny/mvc/controller/UseRestController.java b/mvc/src/main/java/cn/bunny/mvc/controller/UseRestController.java index b75156e..f4aa7a5 100644 --- a/mvc/src/main/java/cn/bunny/mvc/controller/UseRestController.java +++ b/mvc/src/main/java/cn/bunny/mvc/controller/UseRestController.java @@ -16,4 +16,11 @@ public class UseRestController { modelAndView.addObject("message", "这是消息内容"); return modelAndView; } + + @GetMapping("page/test2") + public ModelAndView test2(ModelAndView modelAndView) { + modelAndView.addObject("hello", "你好"); + modelAndView.setViewName("page/test2"); + return modelAndView; + } } diff --git a/mvc/src/main/resources/templates/page/test2.html b/mvc/src/main/resources/templates/page/test2.html new file mode 100644 index 0000000..01501a7 --- /dev/null +++ b/mvc/src/main/resources/templates/page/test2.html @@ -0,0 +1,10 @@ + + + + + 在控制器方法上使用ModelAndView + + +

在控制器方法上使用ModelAndView

+ + \ No newline at end of file diff --git a/mvc/src/main/resources/templates/page/test3.html b/mvc/src/main/resources/templates/page/test3.html new file mode 100644 index 0000000..0f63b37 --- /dev/null +++ b/mvc/src/main/resources/templates/page/test3.html @@ -0,0 +1,10 @@ + + + + + 测试3 + + +

+ + \ No newline at end of file