@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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM