Controller和RestController的区别
1. Controller, RestController的共同点
都是用来表示Spring某个类的是否可以接收HTTP请求。
2. Controller, RestController的不同点
@Controller:标识一个Spring类是Spring MVC controller处理器。@Controller类中的方法可以直接通过返回String跳转到jsp、ftl、html等模版页面。在方法上加@ResponseBody注解,也可以返回实体对象。
@Controller注解源码:
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:@RestController是 @Controller 和 @ResponseBody 的结合体,两个标注合并起来的作用。@RestController类中的所有方法只能返回String、Object、Json等实体对象,不能跳转到模版页面。
@RestController注解源码:
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 "";
}
@RestController中的方法如果想跳转页面,则用ModelAndView进行封装,如下:
@RestController
public class UserController {
@RequestMapping(value = "/index",method = RequestMethod.GET)
public String toIndex(){
ModelAndView mv = new ModelAndView("index");
return mv;
}
}
综上:@RestController注解相当于@ResponseBody + @Controller合在一起的作用。
-
如果只是使用 @RestController 注解Controller,则Controller中的方法无法返回jsp页面,或者html,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
-
如果需要返回到指定页面,则需要用 @Controller 配合视图解析器InternalResourceViewResolver才行。如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
Controller, RestController示例如下:
@Controller
@ResponseBody
public class MyController { }
##等价于
@RestController
public class MyRestController { }
原文链接:https://blog.csdn.net/m0_72151428/article/details/128071558