zoukankan      html  css  js  c++  java
  • Spring @RestController、@Controller区别

    一、用@Controller,返回的是页面;@Controller加上@ResponseBody,返回的是JSON、XML或其他文本。

    @Controller
    @RequestMapping("/test")
    public class MyController1 {
        
        @ResponseBody
        @GetMapping(path="/get1", produces = "text/plain;charset=utf-8")
        public String getMethod1(String str) {
            return str;
        }
    
        @GetMapping(path="/get2", produces = "text/plain;charset=utf-8")
        public String getMethod2(String str) {
            return str;
        }
    }
    

    访问 /test/get1,并携带参数 str="index" ,返回 index 字符串。
    访问 /test/get2,并携带参数 str="index" ,返回名为 index 页面,如index.jsp。

    二、用@RestController,意味着这个Controller的所有方法上面都加了@ResponseBody,不论你在每个方法前加、或不加@ResponseBody,都一样。所以这种Controller不会返回页面。

    @RestController
    @RequestMapping("/test")
    public class MyController1 {
        
        @ResponseBody
        @GetMapping(path="/get1", produces = "text/plain;charset=utf-8")
        public String getMethod1(String str) {
            return str;
        }
    
        @GetMapping(path="/get2", produces = "text/plain;charset=utf-8")
        public String getMethod2(String str) {
            return str;
        }
    }
    

    访问 /test/get1,并携带参数 str="index" ,返回 index 字符串。
    访问 /test/get2,并携带参数 str="index" ,返回 index 字符串。

    参考文章

    @Controller和@RestController的区别?



    作者:KardelShaw
    链接:https://www.jianshu.com/p/c89a3550588a
    来源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
  • 相关阅读:
    CF547D Mike and Fish
    CF147B Smile House
    [BJOI2017]树的难题
    AT2306 Rearranging
    复利计算器--单元测试
    操作系统 实验1 命令解释程序的编写
    个人项目耗时对比记录表
    复利计算器3.0
    0320记《构建之法》读后感
    复利计算实验总结
  • 原文地址:https://www.cnblogs.com/telwanggs/p/11401640.html
Copyright © 2011-2022 走看看