@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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • windows10 Linux子系统(wsl)文件目录

    windows10 Linux子系统(wsl)文件目录简介使用window中的Linux子系统创建的文件究竟放在什么地方,既然作为子系统文件肯定是可以互相访问的目录ubuntuLinux子系统的目录是在这个目录下C:\Users\用户名\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs现在在…

    2022年6月3日
    910
  • haproxy配置详解_核心交换机配置教程

    haproxy配置详解_核心交换机配置教程Linux Haproxy详细配置教程

    2022年4月20日
    49
  • nginx设置ip访问就跳转域名_php页面跳转方法

    nginx设置ip访问就跳转域名_php页面跳转方法目的:将所有wangqiao123.comabc.wangqiao123.com域名自动跳转到www.wangqiao123.comserver{listen80;server_namewangqiao123.comabc.wangqiao123.com;…

    2022年10月4日
    0
  • tree树形结构_什么是树形结构

    tree树形结构_什么是树形结构一、树的基本概念(1)树(Tree)的概念:树是一种递归定义的数据结构,是一种重要的非线性数据结构。树可以是一棵空树,它没有任何的结点;也可以是一棵非空树,至少含有一个结点。(2)根(Root)

    2022年8月3日
    5
  • conversation pattern_inverted pattern

    conversation pattern_inverted patternSample<paramname=”ConversionPattern”value=”%d[%t]%-5p%c[%x]%X{auth}-Line:%L%m%n”/> %m(message):输出的日志消息%n(newline):換行%d(datetime):输出当前语句运行的时刻%r(runtime):输出程序从运行到执…

    2022年8月22日
    5
  • android之AsyncQueryHandler详解

    官方文档对AsyncQueryHandler的解释非常简洁A helper class to help make handling asynchronousContentResolver queries easier下面解释一番,其实明白之后就会发现,真的就是一句话的事情而已.AsyncQueryHandler:异步的查询操作帮助类,其实它同样可以处理增删改,查询其API便可知

    2022年3月9日
    39

发表回复

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

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