一、@RestController 指定主路径无效踩坑
指定路径时写成了 @RestController(“user”), 测试接口的时候发现无效。
查看源码关于 value
的说明:
这仅仅是建议值, 实际应该使用@RequestMapping("/user")
指定.
package com.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController("/user")
public class UserController {
@GetMapping("/list")
public void list(){
}
}
二、@RestController注解
@RestController注解相当于@ResponseBody + @Controller合在一起的作用。
-
如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,配置的视图解析器InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。
例如:本来应该到success.jsp页面的,则其显示success. -
如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行。
-
如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。
2.1、@RestController注解中value作用
查看@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 (or empty String otherwise)
* @since 4.0.1
*/
@AliasFor(annotation = Controller.class)
String value() default "";
}
@RestController的小括号当中填写的内容,相当于@Service(“”)当中填写的内容,即spring bean的名称;
The value may indicate a suggestion for a logical component name,
to be turned into a Spring bean in case of an autodetected component.
该值可能表示一个逻辑组件名称的建议,在自动检测到组件的情况下,将其转换为Spring bean。
所以如果是要填写路径的话,还是需要使用@RequestMapping(“/user”)才是正确的;