zoukankan      html  css  js  c++  java
  • Spring Boot MVC api返回的String无法关联到视图页面

    1:问题

     使用 @Restcontroller 返回值定义为String 时 无法返回具体的页面 

    @RestController
    public class HelloController {
    
        @GetMapping("/hello")
        public ModelAndView hello(ModelAndView modelAndView){
                modelAndView.addObject("hello","<h1>你好<h1>");
                modelAndView.setViewName("success");
                return modelAndView;
        }
    
        @RequestMapping("/randData")
        public String randData(Map<String, ArrayList<String>> map){
            ArrayList<String> lists = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                lists.add("tom"+new Random().nextInt());
            }
            map.put("data",lists);
            return "success";
        }
    }

    执行后返回

     2 处理:

     @RestController 等价于 @Controller 加上 @ResponseBody. 

    1: 使用@RestController 当我们 返回任何类型 只要不是ModelAndViwer 那么都会被解析为json 数据 这个是由于  @ResponseBody. 起作用,

    2:  使用@Controller 当我们 返回String 不会被解析为json 数据 而返回为一个页面,

    总结:

    !1: 使用 @@RestController 返回带有视图 必须使用 ModelAndViwer 当然没有viwer 也可以使用 model map list 等一些数据结构

     2: 使用@Controller 就按照以前使用Spring MVC 的思路进行

  • 相关阅读:
    博客园代码
    前端
    1338. Reduce Array Size to The Half
    1220. Count Vowels Permutation
    363. Max Sum of Rectangle No Larger Than K
    366. Find Leaves of Binary Tree
    443. String Compression
    8 · Rotate String
    886. Possible Bipartition
    LT 183 wood cut
  • 原文地址:https://www.cnblogs.com/dgwblog/p/11957332.html
Copyright © 2011-2022 走看看