1:@RestController
那么这个注解和@Controller有什么区别?
嗯哼,事情开始变得有意思起来了
1. Controller, RestController的共同点
都是用来表示spring某个类的是否可以接收HTTP请求
2. Controller, RestController的不同点
@Controller标识一个Spring类是Spring MVC controller处理器
@RestController: @RestController是@Controller和@ResponseBody的结合体,两个标注合并起来的作用。
下面是@RestController的源码,看了之后你会更清晰的看出来他们之间的区别 * Copyright 2002-2016 the original author or authors.
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;
/**
* A convenience annotation that is itself annotated with
* {@link Controller @Controller} and {@link ResponseBody @ResponseBody}.
* <p>
* Types that carry this annotation are treated as controllers where
* {@link RequestMapping @RequestMapping} methods assume
* {@link ResponseBody @ResponseBody} semantics by default.
*
* <p><b>NOTE:</b> {@code @RestController} is processed if an appropriate
* {@code HandlerMapping}-{@code HandlerAdapter} pair is configured such as the
* {@code RequestMappingHandlerMapping}-{@code RequestMappingHandlerAdapter}
* pair which are the default in the MVC Java config and the MVC namespace.
* In particular {@code @RestController} is not supported with the
* {@code DefaultAnnotationHandlerMapping}-{@code AnnotationMethodHandlerAdapter}
* pair both of which are also deprecated.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
* @since 4.0
*/
@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 "";
}
这里需要注意一点:当你在springboot中使用模板模式返回一个字符串去匹配对应的页面的时候,方法所在的类是不能使用@RestController而应该使用@Controller,为什么?看上面。当然,如果http请求是通过ajax发送到服务端,还是要使用@RestController注解的。