Spring RestController annotation is a convenience annotation that is itself annotated with @Controller and @ResponseBody. This annotation is applied to a class to mark it as a request handler.

Spring RestController注释是一个方便注释,它本身使用@Controller和@ResponseBody注释。 该注释将应用于一个类,以将其标记为请求处理程序。

Spring RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the defined request handler method. Once response body is generated from the handler method, it converts it to JSON or XML response.

Spring RestController批注用于使用Spring MVC创建RESTful Web服务。 Spring RestController负责将请求数据映射到定义的请求处理程序方法。 从处理程序方法生成响应主体后,它将其转换为JSON或XML响应。

Spring RestController示例 (Spring RestController Example)

Let’s see how easily we can use RestController to create a REST web service in Spring. We will reuse the Spring Repository implementation and create a restful webservice.

让我们看看在Spring中使用RestController创建REST Web服务有多么容易。 我们将重用Spring Repository实现并创建一个宁静的Web服务。

We will create a standalone Web application and not use Spring Boot here. We will also expose our APIs to support both JSON and XML in request and response.

我们将在这里创建一个独立的Web应用程序,而不使用Spring Boot。 我们还将在请求和响应中公开支持JSON和XML的API。

Below image shows our final project structure.

下图显示了我们的最终项目结构。

Model and Repository classes are already provided in the Spring Repository tutorial. We will focus more on RestController implementation here.

Spring Repository教程中已经提供了Model和Repository类。 我们将在这里更多地关注RestController的实现。

Spring RestController Maven依赖关系 (Spring RestController Maven Dependencies)

Let’s have a look at the dependencies required to create our Spring RestController example project.

让我们看一下创建Spring RestController示例项目所需的依赖项。

<dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.0.7.RELEASE</version>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.0.7.RELEASE</version>
</dependency><!-- Jackson for REST JSON Support -->
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.6</version>
</dependency>
<!-- JAXB for XML Response, needed to explicitly define from Java 9 onwards -->
<dependency><groupId>javax.xml.bind</groupId><artifactId>jaxb-api</artifactId><version>2.3.0</version>
</dependency>
<dependency><groupId>org.glassfish.jaxb</groupId><artifactId>jaxb-runtime</artifactId><version>2.3.0</version><scope>runtime</scope>
</dependency>
<dependency><groupId>javax.activation</groupId><artifactId>javax.activation-api</artifactId><version>1.2.0</version>
</dependency>

We need Spring MVC, Jackson and JAXB libraries to support both XML and JSON requests and responses from our REST web service.

我们需要Spring MVC,Jackson和JAXB库来支持XML和JSON请求以及来自REST Web服务的响应。

Our web.xml file is used to configure Spring MVC DispatcherServlet as the front controller.

我们的web.xml文件用于将Spring MVC DispatcherServlet配置为前端控制器。

Let’s look at the Spring Context file now.

现在让我们看一下Spring Context文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans:beansxmlns="https://www.springframework.org/schema/mvc"xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"xmlns:beans="https://www.springframework.org/schema/beans"xmlns:context="https://www.springframework.org/schema/context"xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsdhttps://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsdhttps://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!-- Enables the Spring MVC @Controller programming model --><annotation-driven /><context:component-scanbase-package="com.journaldev.spring" /><beans:bean id="jsonMessageConverter"class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /><beans:bean id="xmlMessageConverter"class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" /><beans:beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"><beans:property name="messageConverters"><beans:list><beans:ref bean="jsonMessageConverter" /><beans:ref bean="xmlMessageConverter" /></beans:list></beans:property></beans:bean></beans:beans>

Most important part is the jsonMessageConverter and xmlMessageConverter beans defined and set in the RequestMappingHandlerAdapter messageConverters property. That’s all is needed to tell spring that we want our application to support both JSON and XML and these are the beans to be used for transformation.

最重要的部分是在RequestMappingHandlerAdapter messageConverters属性中定义和设置的jsonMessageConverterxmlMessageConverter Bean。 告诉Spring我们需要所有这些来支持我们的应用程序同时支持JSON和XML,并且这些都是用于转换的bean。

Spring RestController类 (Spring RestController Class)

Here is our Spring RestController class implementation.

这是我们的Spring RestController类的实现。

package com.journaldev.spring.controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;import com.journaldev.spring.model.Employee;
import com.journaldev.spring.repository.EmployeeRepository;@RestController
public class EmployeeRestController {@Autowiredprivate EmployeeRepository repository;@GetMapping("/rest/employee/get/{id}")public Employee getEmployeeByID(@PathVariable("id") int id) {return repository.retrieve(id);}@GetMapping("/rest/employee/getAll")//Returning is List is supported with JSON response only//If you want XML, then add a wrapper class as Root XML element, for example EmployeeListpublic List<Employee> getAllEmployees() {return repository.getAll();}@PostMapping("/rest/employee/create")public Employee createEmployee(@RequestBody Employee emp) {repository.store(emp);return emp;}@GetMapping("/rest/employee/search/{name}")public Employee getEmployeeByName(@PathVariable("name") String name) {return repository.search(name);}@DeleteMapping("/rest/employee/delete/{id}")public Employee deleteEmployeeByID(@PathVariable("id") int id) {return repository.delete(id);}
}

Notice that we have only defined our REST APIs here, all the business logic is part of Repository class.

注意,这里我们仅定义了REST API,所有业务逻辑都是Repository类的一部分。

If our method is returning a list or array, then spring will only support JSON response because XML root element can’t be anonymous but JSON can.

如果我们的方法返回列表或数组,那么spring将仅支持JSON响应,因为XML根元素不能匿名,而JSON可以。

If you want to support returning list as XML, then you will have to create a wrapper class to hold this list and return it.

如果要支持以XML返回列表,则必须创建一个包装器类来保存此列表并返回它。

We are expecting Employee object as the request in some of the methods, Spring will take care of parsing the request body and converting it to the Employee object for these methods.

我们期望在某些方法中将Employee对象作为请求,Spring将负责解析请求主体并将这些方法转换为Employee对象。

Similarly, we are returning Employee object as the Response Body, again Spring will take care of converting it to JSON/XML response.

同样,我们将Employee对象作为Response Body返回,Spring会再次将其转换为JSON / XML响应。

接受和内容类型请求标头 (Accept and Content-Type Request Headers)

We have configured our REST application to work with both XML and JSON. So how it will know that whether the request is XML or JSON. And if the response should be sent in JSON or XML format. This is where Accept and Content-Type Request Headers are used.

我们已经将REST应用程序配置为可以同时使用XML和JSON。 因此,它将如何知道请求是XML还是JSON。 以及是否应以JSON或XML格式发送响应。 这是使用“ Accept和“ Content-Type请求标头”的地方。

Content-Type: Defined the type of content in request body, if its value is “application/xml” then Spring will treat request body as XML document. If its value is “application/json” then the request body is treated as JSON.

Content-Type :定义了请求主体中内容的类型,如果其值为“ application / xml”,那么Spring将把请求主体视为XML文档。 如果其值为“ application / json”,则请求正文被视为JSON。

Accept: Defined the type of content client is expecting as response. If its value is “application/xml” then XML response will be sent. If its value is “application/json” then JSON response will be sent.

接受 :定义客户端期望作为响应的内容类型。 如果其值为“ application / xml”,则将发送XML响应。 如果其值为“ application / json”,则将发送JSON响应。

Spring RestController测试 (Spring RestController Test)

Our application is ready to be tested, I have deployed it on Tomcat-9 and testing with Postman. Below are the testing results with the explanation.

我们的应用程序已准备好进行测试,我已经将其部署在Tomcat-9上并通过Postman进行了测试。 以下是测试结果及其说明。

Spring RestController GET JSON响应 (Spring RestController GET JSON Response)

It’s a simple GET request, the important point to note is the value of “Accept” header.

这是一个简单的GET请求,需要注意的重要一点是“ Accept”标头的值。

Spring RestController GET XML响应 (Spring RestController GET XML Response)

When we changed “Accept” header value to “application/xml”, we are getting XML response.

当我们将“ Accept”标头值更改为“ application / xml”时,我们得到了XML响应。

Spring RestController GET列表 (Spring RestController GET List)

Let’s try to call the API to get list of employees.

We are getting list of elements in JSON with anonymous root element.

让我们尝试调用API以获取员工列表。

我们正在获取带有匿名根元素的JSON中的元素列表。

Since XML doesn’t support anonymous root element, we are getting exception message.

由于XML不支持匿名根元素,因此我们收到了异常消息。

Spring RestController POST (Spring RestController POST)

Spring RestController POST with JSON Request and Response

Spring RestController POST带有JSON请求和响应

Spring RestController POST with JSON Request Body

Spring RestController POST与JSON请求正文

Spring RestController POST with JSON Request and XML Response

Spring RestController POST带有JSON请求和XML响应

Spring RestController删除 (Spring RestController DELETE)

摘要 (Summary)

Spring RestController helps us in focusing on business logic by taking care of all the boiler-plate stuffs for creating REST web services APIs.

Spring RestController通过处理创建REST Web服务API的所有样板内容,帮助我们专注于业务逻辑。

GitHub Repository.GitHub Repository下载完整的项目。

翻译自: https://www.journaldev.com/21536/spring-restcontroller

Spring RestController相关推荐

  1. java controller 继承_java – Spring RestController中的继承

    我有一个Spring RestController,它处理API调用的第1版. package rest.v1; @RestController @RequestMapping("v1/so ...

  2. Spring @RestController、@Controller区别

    一.用@Controller,返回的是页面:@Controller加上@ResponseBody,返回的是JSON.XML或其他文本. @Controller @RequestMapping(&quo ...

  3. spring里面 @Controller和@RestController注解的区别

    问题:spring里面 @Controller和@RestController注解的区别 spring里面 @Controller和@RestController注解的区别 Web MVC和REST ...

  4. 用Spring Cloud和异步微服务进行无服务器计算

    在本文中,我将向您介绍一个使用SpringCloud运行异步微服务的示例,其中每个任务(读微服务)都没有专用服务器(无服务器). 让我先澄清一些术语,然后在这些术语基础上构建示例. ◆ ◆ ◆  ◆  ...

  5. osgi框架和spring区别_最新100道大厂高频spring面试题附答案

    简介 这里是由多位互联网大厂架构师面试整理的出现频率最高的spring相关面试题,并为大家整理了完整的答案,赶紧收藏起来吧! 100道spring高频面试题 Spring概览 1.Spring是什么? ...

  6. java filereader blob_如何从javascript发送音频blob到java spring服务...

    我正在使用RecordRTC在我的javascript客户端录制一些音频数据.我想通过WebSockets将这个音频数据发送到我的Spring RestController. 录制后我在我的javas ...

  7. spring react_使用Spring WebFlux构建React性REST API –第3部分

    spring react 在上一篇文章的续篇中,我们将看到一个应用程序以公开React性REST API. 在此应用程序中,我们使用了 带有WebFlux的Spring Boot 具有响应式支持的Ca ...

  8. 使用Spring开发Java RESTful Web服务的7个理由

    REST现在已成为开发Web服务的标准方法,涉及Java时,可以使用许多框架和库,例如JAX-RS,Restlet,Jersey,RESTEasy,Apache CFX等,但是我鼓励Java开发人员使 ...

  9. 将Swagger与Spring Boot REST API集成

    在上一篇文章中,我谈到了我使用Spring Boot创建RESTFul Services的经验. 在创建REST API时,正确的文档是其中的必需部分. 昂首阔步是什么? Swagger (Swagg ...

最新文章

  1. Node.js实现服务器端生成Excel文件(xls格式、xlsx格式文件)并弹出下载文件
  2. fcitx输入法在wps、wineqq中失灵问题的解决
  3. matlab 系统辨识工具箱,MATLAB系统辨识工具箱的应用.ppt
  4. 新兴的多媒体格式——MXF 文件格式分析 和简介
  5. DirectShow组件原理分析及应用
  6. Mac OS X 显示和隐藏文件
  7. 【clickhouse】clickhouse Uint64 不是64位 超限不报错
  8. Kotlin入门(20)几种常见的对话框
  9. cocos2dx box2d使用(一)
  10. rs422/rs485通信接口原理图
  11. IDEA git 切换分支注意事项(好文章!!)
  12. Excel绘制排名变化曲线图(折线图),附源文件
  13. 平衡电枢磁性扬声器行业调研报告 - 市场现状分析与发展前景预测
  14. 华为手机8.0.0怎么找到云相册_华为手机里的相册照片删除了怎么找回?
  15. c++ getline()详解
  16. 互联网模式OTO、C2C、B2B、B2C名词
  17. 找回XShell保存过的密码
  18. Kindle电子书的制作
  19. 多变量线性回归(机器学习笔记三)
  20. 电能质量监测平台95概率大值统计流程设计优化

热门文章

  1. Unity Editor Toolbar 编辑器扩展
  2. Cassandra 之旅 (二) Getting Started
  3. 编译android源码四(常见错误)
  4. 使用特殊字体实现特殊报表效果
  5. [转载] python iter( )函数
  6. [转载] numpy教程:排序、搜索和计数
  7. SpringCloud学习指南【更新】
  8. linux翻转字符串
  9. mysql慢查询日志分析工具(python写的)
  10. 怎样快速更新已安装的软件?