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


相关推荐

  • 使用vue.js安装node环境npm出错npm ERR! network request to https://registry.npmjs.org/nrm failed, reason: conn[通俗易懂]

    使用vue.js安装node环境npm出错npm ERR! network request to https://registry.npmjs.org/nrm failed, reason: conn[通俗易懂]报错信息:npmERR!codeETIMEDOUTnpmERR!errnoETIMEDOUTnpmERR!networkrequesttohttps://registry.npmjs.org/nrmfailed,reason:connectETIMEDOUT104.16.20.35:443npmERR!networkThisisaproblem…

    2022年10月29日
    0
  • 简单易懂的softmax交叉熵损失函数求导

    简单易懂的softmax交叉熵损失函数求导来写一个softmax求导的推导过程,不仅可以给自己理清思路,还可以造福大众,岂不美哉~softmax经常被添加在分类任务的神经网络中的输出层,神经网络的反向传播中关键的步骤就是求导,从这个过程也可以更深刻地理解反向传播的过程,还可以对梯度传播的问题有更多的思考。softmax函数softmax(柔性最大值)函数,一般在神经网络中,softmax可以作为分类任务的输出层。其实可…

    2022年6月26日
    22
  • Java 取余 (remain),取模 (mod) 的 区别和运算

    Java 取余 (remain),取模 (mod) 的 区别和运算Java取余(remain),取模(mod)的区别和运算范围区别:取模主要是用于计算机术语中。取余则更多是数学概念。主要的区别在于对负整数进行除法运算时操作不同那么具体是怎样的不同?首先需要知道Java中如何取模:Java中用符号%对数字进行取模,可以得到以下:System.out.println(5%3);System.out.println(-5%3);Sys…

    2022年6月3日
    114
  • Android 串口调试_串口转usb需要驱动吗

    Android 串口调试_串口转usb需要驱动吗本文背景:是真的不喜欢脑子记这些引脚,串口节点,动不动忘记了。1.首先记录一下硬件引脚—-tty节点对应关系2.找一组/dev/ttyHSL1,先测试一下自环,然后写个app,从app里面读写这个节点3.后续,通过串口和单片机通信,和esp8266通信,实现一个androidapp控制单片机硬件平台配置:平台:msm8909默认log串口:Board_KERNEL_CMDLINE.

    2022年10月10日
    0
  • 基于python的快速傅里叶变换FFT(二)

    基于python的快速傅里叶变换FFT(二)

    2021年11月21日
    42
  • 在pycharm中安装pip_pycharm安装django

    在pycharm中安装pip_pycharm安装django转载地址:http://www.cnblogs.com/yuanzm/p/4089856.htmlPython,最近又开始玩起了这门语言。总的来说,个人很喜欢Python的语言风格,但是这门语言对于windows并不算很友好,因为如果是初学者在windows环境下安装,简直是折磨人,会遇到各种蛋疼的情况。本文希望提供傻瓜式的教程,能够令读者成功安装Python和pip。第一步,我们先来安装Py…

    2022年8月27日
    0

发表回复

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

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