1. 程式人生 > >@Controller和@RestController區別

@Controller和@RestController區別

@controller spring @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註解


@Controller和@RestController區別