• @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 

  • 相关阅读:
    Mac下mysql出现错误:ERROR 1055 (42000)
    单表查询
    外键的变种 三种关系
    Java8中Lambda表达式详解
    Java中的比较器Comparable、Comparator
    Java创建线程的方法
    java日期格式化
    Docker容器如何修改hosts
    使用postman可以正常访问,但是在应用中返回415状态码
    使用tcpdump进行抓包
  • 原文地址:https://www.cnblogs.com/hello-tl/p/9202658.html
Copyright © 2020-2023  润新知