@RestController的作用「建议收藏」

@RestController的作用「建议收藏」原文:文章收藏于IT老兵博客。正文理解一下@RestControlle的作用。ThiscodeusesSpring4’snew @RestController annotation,whichmarkstheclassasacontrollerwhereeverymethodreturnsadomainobjectinsteadofa…

大家好,又见面了,我是你们的朋友全栈君。

原文:

文章收藏于IT老兵博客

正文

理解一下@RestControlle的作用。

This code uses Spring 4’s new @RestController annotation, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.

上文摘自官网

由上面可见,@RestController=@Controller+@ResponseBody,下一步,理解@Controller。

Classic controllers can be annotated with the @Controller annotation. This is simply a specialization of the @Component class and allows implementation classes to be autodetected through the classpath scanning.

@Controller is typically used in combination with a @RequestMapping annotation used on request handling methods.

摘自这里,可以看出以下几点:

  1. @Controller 是一种特殊化的@Component 类。
  2. @Controller 习惯于和@RequestMapping绑定来使用,后者是用来指定路由映射的。

下一步,理解@ResponseBody。

The request handling method is annotated with @ResponseBody. This annotation enables automatic serialization of the return object into the HttpResponse.

摘自同样的地方,这里可以看出:

  1. @ResponseBody 是用来把返回对象自动序列化成HttpResponse的。

再参考这里

3. @ResponseBody

The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

Suppose we have a custom Response object:

1

2

3

4

5

public class ResponseTransfer {

    private String text;

     

    // standard getters/setters

}

Next, the associated controller can be implemented:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@Controller

@RequestMapping("/post")

public class ExamplePostController {

 

    @Autowired

    ExampleService exampleService;

 

    @PostMapping("/response")

    @ResponseBody

    public ResponseTransfer postResponseController(

      @RequestBody LoginForm loginForm) {

        return new ResponseTransfer("Thanks For Posting!!!");

     }

}

In the developer console of our browser or using a tool like Postman, we can see the following response:

1

{"text":"Thanks For Posting!!!"}

Remember, we don’t need to annotate the @RestController-annotated controllers with the @ResponseBody annotation since it’s done by default here.

从上面可以看出:

  1. @ResponseBody告诉控制器返回对象会被自动序列化成JSON,并且传回HttpResponse这个对象。

再补充一下@RequestBody

Simply put, the @RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object.

First, let’s have a look at a Spring controller method:

1

2

3

4

5

6

7

@PostMapping("/request")

public ResponseEntity postController(

  @RequestBody LoginForm loginForm) {

  

    exampleService.fakeAuthenticate(loginForm);

    return ResponseEntity.ok(HttpStatus.OK);

}

Spring automatically deserializes the JSON into a Java type assuming an appropriate one is specified. By default, the type we annotate with the @RequestBody annotation must correspond to the JSON sent from our client-side controller:

1

2

3

4

5

public class LoginForm {

    private String username;

    private String password;

    // ...

}

Here, the object we use to represent the HttpRequest body maps to our LoginForm object.

Let’s test this using CURL:

1

2

3

4

5

curl -i \

-H "Accept: application/json" \

-H "Content-Type:application/json" \

-X POST --data

  '{"username": "johnny", "password": "password"}' "https://localhost:8080/.../request"

This is all that is needed for a Spring REST API and an Angular client using the @RequestBody annotation!

@RequestBodyHttpRequest body映射成一个 transfer or domain object(DTO或者DO),把一个入境(inbound)的HttpRequest的body反序列化成一个Java对象。

参考

https://spring.io/guides/gs/rest-service/

https://www.baeldung.com/spring-controller-vs-restcontroller

https://www.baeldung.com/spring-request-response-body

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/149858.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 构建高并发高可用的电商平台架构实践[通俗易懂]

    构建高并发高可用的电商平台架构实践[通俗易懂]各个维度总结电商平台中的高并发高可用的架构实践,从架构设计的理念到平台的逻辑架构,以及到平台架构中各个模块的介绍

    2022年6月30日
    35
  • 视频编码的常见参数基本概念 –bit rate / frame rate /sample rate等等

    视频编码的常见参数基本概念 –bit rate / frame rate /sample rate等等码率:Bit Rate,指视频或音频文件在单位时间内使用的数据流量,该参数的单位通常是Kbps,也就是千比特每秒。通常2000kbps~3000kbps就已经足以将画质效果表现到极致了。码率参数与视频文件最终体积大小有直接性的关系。  混合码率:Overall Bit Rate,指视频文件中视频和音频混合后的整体平均码率。一般描述一个视频文件的码率都是指OBR,如新浪播客允许的OBR上

    2022年10月9日
    3
  • jquery判断数组中是否包含某个元素的值_java判断元素是否在数组中

    jquery判断数组中是否包含某个元素的值_java判断元素是否在数组中$.inArray(“元素字符串”,数组名称);vararry=[“C#”,”html”,”css”,”JavaScript”];varresult=$.inArray(“C#”,arry);如果arry数组里面存在”C#”这个字符串则返回该字符串的数组下标,否则返回(不包含在数组中)-1…

    2022年10月18日
    2
  • Java大数据学习路线图

    Java大数据学习路线图Java大数据学习路线图准备篇适用/适合人群:适合基础小白在这里还是要推荐下我自己建的大数据学习群:199427210,群里都是学大数据开发的,如果你正在学习大数据,小编欢迎你加入,大家都是软件开发党,不定期分享干货(只有大数据软件开发相关的),包括我自己整理的一份最新的大数据进阶资料和高级开发教程,欢迎进阶中和进想深入大数据的小伙伴加入。目标:掌握JavaS…

    2022年5月8日
    40
  • git 命令怎么删除远程分支文件_git删除远程仓库分支

    git 命令怎么删除远程分支文件_git删除远程仓库分支本地删除请看:git命令怎么删除本地分支查看所有分支查看项目的远程分支:gitbranch-r删除远程分支比如我们要删除远程分支origin/SLT_table_reportgitpushorigin-d分支名我们执行:gitpushorigin-dSLT_table_report删除成功注意这里不能写成origin/SLT_table_report,不然会报错:具体请参考【git删除远程分支报错error:unabletodelete‘

    2022年10月16日
    3
  • vue入门教程(一)「建议收藏」

    vue入门教程(一)「建议收藏」1.vue简介1.1vue是什么官网:https://cn.vuejs.org/Vue是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是,Vue被设计为可以自底向上逐层应用。Vue的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合。另一方面,当与现代化的工具链以及各种支持类库结合使用时,Vue也完全能够为复杂的单页应用提供驱动。1.2vue的特点1)遵循MVVM模式2)编码简洁,体积小,运行效率高,适合移动/PC端开发.

    2022年6月4日
    33

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号