@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 

原文地址:https://www.cnblogs.com/hello-tl/p/9202658.html