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


相关推荐

  • [日常办公][Ubuntu]proxy settings

    [日常办公][Ubuntu]proxy settingsbashproxyexporthttp_proxy=XXXexporthttps_proxy=XXXaptproxysudovim/etc/apt/apt.confAcquire::http::proxy”http://XXX”;Acquire::https::proxy”https://XXX”;Acquire::ftp::proxy”ftp://XXX”;Acquire::socks::proxy”socks://XXX”;dockerproxymkdir

    2022年7月21日
    11
  • 【全套完结】数字信号处理—-全套Matlab实验报告【建议保存】「建议收藏」

    目录实验一、熟悉MATLAB环境和基本信号的产生与运算实验一、熟悉MATLAB环境和基本信号的产生与运算实验一、熟悉MATLAB环境和基本信号的产生与运算

    2022年4月8日
    38
  • 几个国外SPS技术网站

    几个国外SPS技术网站http://www.tech-archive.net/Archive/SharePoint/microsoft.public.sharepoint.portalserver.development/http://weblogs.asp.net/autocrat/archive/2004/11/10/254825.aspxhttp://www.mev.com/modules/lists/msft/…

    2022年6月22日
    35
  • 数据库置疑修复方法_msdb数据库置疑的解决方法

    数据库置疑修复方法_msdb数据库置疑的解决方法SQL2000数据库置疑解决方法置疑可能是因为磁盘空间不够或者是日志文件损坏再或者操作时主机突然掉电造成的DB为改名后的数据库,实际要导入的是SMPDB数据库1:新建一个不同名的数据库2:停掉SQLSERVER3:在C:/ProgramFiles/MicrosoftSQLServer/MSSQL/Data中用备份的数据库MDF的文件覆盖掉这个数据库文件4:重启SQL5:执行以下语句紧急打开置疑的数据库(注意空格)数据库紧急打开代码如下: USEMASTER  GO  SP_CONF

    2022年8月20日
    9
  • hive的元数据存储在derby和mysql_桌面云必须部署的组件包括

    hive的元数据存储在derby和mysql_桌面云必须部署的组件包括搭建hive的环境需要hadoop的dfs和yarn可以正常运行的情况下。准备好apache-hive-1.2.1-bin.tar.gz和mysql-libs.zip两个包hive安装步骤:解压apache-hive-1.2.1-bin.tar.gz到/usr/local/src下,并且将其重命名为hivetar-zxvfapache-hive-1.2.1-bin.tar.gzmvapache-hive-1.2.1-binhive复制/hive/conf下的hive-en.

    2025年6月19日
    0
  • java里的全局变量_全局变量的值会不会改变

    java里的全局变量_全局变量的值会不会改变在类定义(声明)了全局变量,没有对其赋值,利用类内的方法对其赋值,其值变成了方法给的值,无论是在方法内部还是方法外。(除非你定义了同名的局部变量)

    2022年8月21日
    12

发表回复

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

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