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


相关推荐

  • phpstrom 激活码 2021_通用破解码

    phpstrom 激活码 2021_通用破解码,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月16日
    62
  • ES 安装 elasticsearch-sql插件「建议收藏」

    ES 安装 elasticsearch-sql插件「建议收藏」1、查看sql插件githubhttps://github.com/NLPchina/elasticsearch-sql2、安装1、cdelasticsearch#进入目录2、./bin/elasticsearch-plugininstallhttps://github.com/NLPchina/elasticsearch-sql/releases/download/5.4.3.0/elasticsearch-sql-5.4.3.0.zip3、下载SQL的Serverwget

    2022年6月21日
    40
  • 网站的404错误页面制作方法[通俗易懂]

    网站的404错误页面制作方法[通俗易懂]网站的404错误页面怎么做?  网站的404错误页面怎么做呢?很多人学习完seo就对404错误页面的理解有所偏差,认为404错误页面只是为了SEO而存在,实际上,404错误页面不单只是为了seo而存在,它一共提出以下几点理念:  一、提供简明的问题描述,消除访客的挫败感。这个很好理解,告诉用户访问页面不存在,而不会是系统默认的错误页面。  二、提供合理的解决方案,辅助访客完成访问目标。

    2022年7月27日
    29
  • 国产的FPGA_能不能长点心

    国产的FPGA_能不能长点心关注、星标公众号,直达精彩内容FPGA作为嵌入式必备的一个硬件,国产的产品也正在逐渐渗透工程师的生活之中。不过tzgok认为,目前国产FPGA还有几个问题非常令人困扰,并发出评论表示“国产…

    2025年11月11日
    7
  • mina框架学习

      一、mina简介    mina框架是对nio进行的一个封装,可用于java的网络编程,包括TCP/IP和UTP/IP编程,主要屏蔽了网络通信的一些细节,对socket进行封装,并且是用nio的一个实现框架,mina的主要类如下: 1、IoService接口用于描述客户端和服务端的接口,子类有IoConnector(客户端)和IoAcceptor(服务端)。1….

    2022年4月6日
    37
  • dos的批量copy命令

    dos的批量copy命令1、主要是有需求,采取百度的,发现挺好的,还是帮作者推广一下。来自https://www.cnblogs.com/xiykj/archive/2004/01/13/13299548.html“Dos命令复制所有目录下同类型文件”2、需求:想拷贝文件夹内部的同类型文件(比如*.jpg),但是这个jpg文件在不同的文件夹下面,因此copy起来还是不方便,因此需要寻求命令代码解决3、命令是:for/r%iin(.jpg)*docopy“%i”/yd:\img其中,加粗的是变成自己需

    2022年7月18日
    21

发表回复

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

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