controller和Restcontroller的区别
获取中...
1. Controller, RestController的共同点
都是用来表示Spring某个类的是否可以接收HTTP请求。
2. Controller, RestController的不同点
@Controller:标识一个Spring类是Spring MVC controller处理器,@RestController:@RestController是@Controller和@ResponseBody的结合体,两个标注合并起来的作用。@Controller类中的方法可以直接通过返回String跳转到jsp、ftl、html等模版页面。在方法上加@ResponseBody注解,也可以返回实体对象。@RestController类中的所有方法只能返回String、Object、Json等实体对象,不能跳转到模版页面。
@RestController中的方法如果想跳转页面,则用ModelAndView进行封装,如下:
1 2 3 4 5 6 7 8 9
| @RestController public class UserController { @RequestMapping(value = "/index",method = RequestMethod.GET) public String toIndex(){ ModelAndView mv = new ModelAndView("index"); return mv; } }
|
示例如下:
1 2 3 4 5 6
| @Controller @ResponseBody public class MyController { } @RestController public class MyRestController { }
|
@Controller注解源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package org.springframework.stereotype; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.stereotype.Component; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Controller { String value() default ""; }
|
@RestController注解源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| package org.springframework.web.bind.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ResponseBody; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Controller @ResponseBody public @interface RestController { String value() default ""; }
|
本文由 rufus 创作,采用 知识共享署名 4.0 国际许可协议。
本站文章除注明转载/出处外,均为本站原创或翻译,转载请务必署名。