初识springboot中的@Controller和@RestController

目录

第一,两者的区别

第二,如何使用


参考文献:

https://www.cnblogs.com/jxwy/p/6797420.html

https://www.cnblogs.com/shuaifing/p/8119664.html

第一,两者的区别

@Controller和@RestController的区别?
官方文档:
@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
意思是:
@RestController注解相当于@ResponseBody + @Controller合在一起的作用。

看一下RestController的源码,就能清晰的知晓其功能:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(
        annotation = Controller.class
    )
    String value() default "";
}

第二,如何使用

1) 如果只是使用@RestController注解Controller,则Controller中的方法无法返回jsp页面,或者html,配置的视图解析器 InternalResourceViewResolver不起作用,返回的内容就是Return 里的内容。

@RestController
public class HelloWorld {
    @RequestMapping("/hello")
    public String  test(){
        return "hello";
    }
}

2) 如果需要返回到指定页面,则需要用 @Controller配合视图解析器InternalResourceViewResolver才行(简言之就是返回界面)。如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

@Controller
public class HelloWorld {
    @RequestMapping("/hello")
    public String  test(){
        return "hello";
    }
}

没有hello这样的界面,就报错了。

初识springboot中的@Controller和@RestController_第1张图片

改成index即可(一个存在的界面)

@Controller
public class HelloWorld {
    @RequestMapping("/hello")
    public String  test(){
        return "index";
    }
}

初识springboot中的@Controller和@RestController_第2张图片

3)如果需要返回JSON,XML或自定义mediaType内容到页面,则需要在对应的方法上加上@ResponseBody注解。

@Controller
public class HelloWorld {
    @RequestMapping("/hello")
    @ResponseBody
    public String  test(){
        return "index";
    }
}

初识springboot中的@Controller和@RestController_第3张图片

你可能感兴趣的:(spring,注解的区别,RestController,Controller)