Spring RestController注解是一个便利注解,它本身被注解为@Controller和@ResponseBody
。此注解应用于类以将其标记为请求处理程序。Spring RestController注解用于使用Spring MVC创建RESTful Web服务。Spring RestController负责将请求数据映射到定义的请求处理程序方法。一旦从处理程序方法生成响应体,它就会将其转换为JSON或XML响应。
Spring RestController示例
让我们看看如何在Spring中轻松使用RestController来创建REST Web服务。我们将重用Spring Repository实现并创建一个RESTful Web服务。我们将创建一个独立的Web应用程序,并在此处不使用Spring Boot。我们还将公开我们的API以支持请求和响应中的JSON和XML。下面的图像显示了我们的最终项目结构。模型和存储库类已在Spring Repository教程中提供。我们将更多关注RestController的实现。
Spring RestController Maven 依赖
让我们看看创建 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>
我们需要 Spring MVC、Jackson 和 JAXB 库来支持来自我们 REST Web 服务的 XML 和 JSON 请求和响应。我们使用 web.xml 文件来配置 Spring MVC DispatcherServlet 作为前端控制器。现在让我们来看一下 Spring 上下文文件。
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="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.xsd
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://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-scan
base-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:bean
class="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>
最重要的部分是在 RequestMappingHandlerAdapter
的 messageConverters
属性中定义并设置的 jsonMessageConverter
和 xmlMessageConverter
bean。这就是告诉 Spring 我们希望我们的应用程序支持 JSON 和 XML,并且这些是用于转换的 bean。
Spring RestController 类
这是我们的 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 {
@Autowired
private EmployeeRepository repository;
@GetMapping("/rest/employee/get/{id}")
public Employee getEmployeeByID(@PathVariable("id") int id) {
return repository.retrieve(id);
}
@GetMapping("/rest/employee/getAll")
// 返回 List 仅支持 JSON 响应
// 如果你想要 XML,则添加一个包装类作为根 XML 元素,例如 EmployeeList
public List 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);
}
}
请注意,我们在这里只定义了我们的REST API,所有业务逻辑都是Repository类的一部分。如果我们的方法返回一个列表或数组,那么Spring只会支持JSON响应,因为XML根元素不能是匿名的,但JSON可以。如果您想支持将列表作为XML返回,那么您将需要创建一个包装类来保存此列表并返回它。在某些方法中,我们期望请求中有Employee对象,Spring将负责解析请求体并将其转换为Employee对象。同样地,我们将Employee对象作为响应体返回,Spring将负责将其转换为JSON/XML响应。
接受和Content-Type请求头
我们已经配置了我们的REST应用程序以同时与XML和JSON一起工作。那么它如何知道请求是XML还是JSON呢?以及响应应以JSON或XML格式发送。这就是Accept
和Content-Type
请求头派上用场的地方。Content-Type:定义了请求体中内容的类型,如果其值为“application/xml”,则Spring将将请求体视为XML文档。如果其值为“application/json”,则请求体将被视为JSON。Accept:定义了客户端期望的响应内容类型。如果其值为“application/xml”,则将发送XML响应。如果其值为“application/json”,则将发送JSON响应。
Spring RestController 测试
我们的应用程序已准备好进行测试,我已将其部署在 Tomcat-9 上,并使用 Postman 进行测试。以下是测试结果及解释。
Spring RestController GET JSON 响应
这是一个简单的 GET 请求,需要注意的重要点是 “Accept” 头的值。
Spring RestController GET XML 响应
当我们将 “Accept” 头的值更改为 “application/xml” 时,我们会得到 XML 响应。
Spring RestController GET 列表
让我们尝试调用 API 来获取员工列表。我们得到一个具有匿名根元素的 JSON 元素列表。
由于 XML 不支持匿名根元素,我们收到了异常消息。
Spring RestController 发送 POST 请求
Spring RestController 发送 JSON 请求和响应Spring RestController 发送带有 JSON 请求体的 POST 请求
Spring RestController 发送 JSON 请求并返回 XML 响应的 POST 请求
Spring RestController 发送 DELETE 请求
摘要
Spring RestController通过处理创建REST Web服务API的所有样板内容,帮助我们专注于业务逻辑。
您可以从我们的GitHub代码库下载完整的项目。
Source:
https://www.digitalocean.com/community/tutorials/spring-restcontroller