@Controller和@RestController區別

@RestController實現方式:

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@Controller

@ResponseBody

public @interface RestController {

/**

* The value may indicate a suggestion for a logical component name,

* to be turned into a Spring bean in case of an autodetected component.

* @return the suggested component name, if any

* @since 4.0.1

*/

String value() default "";

}

@Controller實現方式:

@Target({ElementType.TYPE})

@Retention(RetentionPolicy.RUNTIME)

@Documented

@Component

public @interface Controller {

/**

* The value may indicate a suggestion for a logical component name,

* to be turned into a Spring bean in case of an autodetected component.

* @return the suggested component name, if any

*/

String value() default "";

}

一目瞭然,@RestController的實現代碼中多了一個@ResponseBody註解,那麼來看@ResponseBody註解的含義:

作用: 

      該註解用於將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換爲指定格式後,寫入到Response對象的body數據區。

使用時機:

      返回的數據不是html標籤的頁面,而是其他某種格式的數據時(如json、xml等)使用;

那麼就得出結果了.

例子:

如果使用@Controller來實現返回數據返回json,那麼方法一般要加上:

@RequestMapping("/getDemoById.do")

@ResponseBody

public Map<String, Object> getUser(long id) {

Map<String, Object> map = new HashMap<String, Object>();

     do someting....

     return map;

}

如果使用@RestController實現返回數據返回json則不用加@ResponseBody註解


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章