@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!

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


相关推荐

  • sigmoid函数解析式_phonetic函数

    sigmoid函数解析式_phonetic函数Sigmoid函数,即f(x)=1/(1+e-x)。是神经元的非线性作用函数。广泛应用在神经网络中。神经网络的学习是基于一组样本进行的,它包括输入和输出(这里用期望输出表示),输入和输出有多少个分量就有多少个输入和输出神经元与之对应。最初神经网络的权值(Weight)和阈值(Threshold)是任意给定的,学习就是逐渐调整权值和阈值使得网络的实际输出和期望输出一致。给定以下的总输

    2022年10月22日
  • python中怎样换行输出_python换行继续输入

    python中怎样换行输出_python换行继续输入python输出换行的方法:1、用转义符号【\n】,代码为【str3=”..\n”】;2、直接用print输出一个空行,代码为【print(str1);print(“”);print(str2)】。本教程操作环境:windows7系统、python3.9版,DELLG3电脑。python输出换行的方法:方法1:用转义符号。str3=”我不见,万古英雄曾拔剑,铁笛高吹龙夜吟\n”st…

    2022年10月30日
  • deepfakes怎么用_黑科技▍如何使用 Deepfakes 给主播换脸?教程来了

    deepfakes怎么用_黑科技▍如何使用 Deepfakes 给主播换脸?教程来了下面放教程:1.获取deepfakes工具包gitclonehttps://github.com/deepfakes/faceswap.git2.补齐依赖包:pipinstalltqdmpipinstallcv2pipinstallopencv-contrib-pythonpipinstalldlibpipinstallkeraspipinstalltensorfl…

    2022年5月26日
  • ws 无法热替换的问题

    ws 无法热替换的问题

    2022年2月23日
  • react中postMessage与addEventListener的使用

    react中postMessage与addEventListener的使用有时候两个页面之间不是父子组件的情况下,信息交互很难搞,看到有人用postmessage来进行消息交互,我也试了一下,哎呀妈真香!!!1、首先在需要发送消息的界面中使用postMessage使用的是React+TypeScript,逻辑是更新提交的时候刷新打开当前页面的父窗口,postMessage用法如下:if(window.opener&&window.opener.location&&window.opener.location.href){

    2022年7月12日
  • python之open函数

    python之open函数1小序功能:打开某个文件,创建一个file对象,调用相关方法进行读写.格式:open(name[,mode[,buffering]])序号参数描述1name2mode3buffering

    2022年5月26日

发表回复

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

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