• @RestController 与 @Controller 注解区别


    文章来源:https://www.cnblogs.com/hello-tl/p/9202658.html 

    @RestController注解相当于@ResponseBody + @Controller合在一起的作用

    //  一般用于接口   或   前后端分离

    1.如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp,html页面,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是return 里的内容。

    // 一般用于后台页面

    2.如果需要返回到指定页面,则需要用   @Controller  配合视图解析器   InternalResourceViewResolver   才行。

    如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

    例如

    1.如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp,html页面,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是return 里的内容。

    package com.web.TestRestController;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @RestController
    @RequestMapping("/TestController")
    public class TestRestController{
    
        // 返回 return 里面的内容
        @RequestMapping(value = "index", method = RequestMethod.GET)
        public String index(){
            // 返回 return 里面的内容 如字符串 json xml 或自定义返回
            return "{}";
        }
    }
    

      

     2.如果需要返回到指定页面,则需要用   @Controller  配合视图解析器   InternalResourceViewResolver   才行。

    如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

    package com.web.TestController;
    
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    @Controller
    @RequestMapping("/TestController")
    public class TestController{
        
        // 映射文件
        @RequestMapping(value = "index", method = RequestMethod.GET)
        public String index(){
            // 他就会映射到 TestController 目录下 index.jsp 或 index.html 文件
            return "TestController/index";
        }
    
        // 返回 return 里面的内容
        @RequestMapping(value = "index", method = RequestMethod.GET)
        @ResponseBody
        public String index(){
            // 返回 return 里面的内容 如字符串 json xml 或自定义返回
            return "{}";
        }
    }
    

    文章来源:https://www.cnblogs.com/hello-tl/p/9202658.html 

  • 相关阅读:
    (24)码表
    (23)IO之打印流 PrintStream & Printwriter
    (22)Properties,这不会Io流中的类,但是通常和IO流中的一些流配合使用
    (21)IO流之对象的序列化和反序列化流ObjectOutputStream和ObjectInputStream
    (20)IO流之SequenceInputStream 序列流
    01.vue基础
    02.1插值操作-Mustache语法
    jQuery对节点的增删改查和一些常用的逻辑处理
    递归 阶乘
    电脑远程连接
  • 原文地址:https://www.cnblogs.com/hello-tl/p/9202658.html
Copyright © 2020-2023  润新知