码迷,mamicode.com
首页 > 其他好文 > 详细

@Controller和@RestController区别

时间:2017-10-12 22:55:12      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:@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区别

标签:@controller   spring   @restcontroller   

原文地址:http://13175699.blog.51cto.com/13165699/1971840

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!