@Controller和@RestController的區別

 

 

 

 

 

 

官方文檔:
@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
意思是:
@RestController註解至關於@ResponseBody + @Controller合在一塊兒的做用。
 java

1)若是隻是使用@RestController註解Controller,則Controller中的方法沒法返回jsp頁面,配置的視圖解析器InternalResourceViewResolver不起做用,返回的內容就是Return 裏的內容。web

例如:原本應該到success.jsp頁面的,則其顯示success.spring

2)若是須要返回到指定頁面,則須要用 @Controller配合視圖解析器InternalResourceViewResolver才行。
3)若是須要返回JSON,XML或自定義mediaType內容到頁面,則須要在對應的方法上加上@ResponseBody註解。json

總結:@RestControllerapp

整個類全部方法再也不返回視圖頁面,所有返回方法中定義的返回內容,好比json:jsp

例如:code

package com.kbs.platform.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/json")
@RestController
public class JsonController {

	@RequestMapping("/map")
	public Map<String, String> getmap(){
		Map<String, String> map=new HashMap<>();
		map.put("a", "b");
		map.put("c", "d");
		map.put("d", "小家心");
		return map;
	}
	
	@RequestMapping("/body")
	public Map<String, String> getmap2(){
		Map<String, String> map=new HashMap<>();
		map.put("a", "b");
		map.put("c", "d");
		map.put("d", "小家心");
		return map;
	}
	
}
//實例二 @ResponseBody + @Controller
//這個類的方法既能夠返回視圖,又能夠返回想要的數據

package com.kbs.platform.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping("/json")
@Controller
public class JsonController {

	//這個方法返回視圖,沒有對應的視圖就會報錯
	@RequestMapping("/map")
	public Map<String, String> getmap(){
		Map<String, String> map=new HashMap<>();
		map.put("a", "b");
		map.put("c", "d");
		map.put("d", "小家心");
		return map;
	}
	//這個方法返回json 再也不返回視圖
	@RequestMapping("/body")
	public Map<String, String> getmap2(){
		Map<String, String> map=new HashMap<>();
		map.put("a", "b");
		map.put("c", "d");
		map.put("d", "小家心");
		return map;
	}
	
}
相關文章
相關標籤/搜索