Spring RestController 注释是一种方便注释,本身注释为 @Controller和 @ResponseBody
. 此注释应用于一个类以标记为请求处理器。 Spring RestController 注释用于使用 Spring MVC 创建 RESTful 网页服务。 Spring RestController 负责将请求数据绘制到定义的请求处理方法。
春天控制器例子
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. 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. 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.
春季控制器 Maven 依赖
让我们看看创建我们的 Spring RestController 示例项目所需的依赖性。
1<dependency>
2 <groupId>org.springframework</groupId>
3 <artifactId>spring-webmvc</artifactId>
4 <version>5.0.7.RELEASE</version>
5</dependency>
6<dependency>
7 <groupId>org.springframework</groupId>
8 <artifactId>spring-web</artifactId>
9 <version>5.0.7.RELEASE</version>
10</dependency>
11
12<!-- Jackson for REST JSON Support -->
13<dependency>
14 <groupId>com.fasterxml.jackson.core</groupId>
15 <artifactId>jackson-databind</artifactId>
16 <version>2.9.6</version>
17</dependency>
18<!-- JAXB for XML Response, needed to explicitly define from Java 9 onwards -->
19<dependency>
20 <groupId>javax.xml.bind</groupId>
21 <artifactId>jaxb-api</artifactId>
22 <version>2.3.0</version>
23</dependency>
24<dependency>
25 <groupId>org.glassfish.jaxb</groupId>
26 <artifactId>jaxb-runtime</artifactId>
27 <version>2.3.0</version>
28 <scope>runtime</scope>
29</dependency>
30<dependency>
31 <groupId>javax.activation</groupId>
32 <artifactId>javax.activation-api</artifactId>
33 <version>1.2.0</version>
34</dependency>
我们需要 Spring MVC、Jackson 和 JAXB 库来支持我们的 REST Web 服务的 XML 和 JSON 请求和响应,我们的 web.xml 文件用于将 Spring MVC DispatcherServlet 配置为前置控制器。
1<?xml version="1.0" encoding="UTF-8"?>
2<beans:beans
3 xmlns="https://www.springframework.org/schema/mvc"
4 xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
5 xmlns:beans="https://www.springframework.org/schema/beans"
6 xmlns:context="https://www.springframework.org/schema/context"
7 xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
8 https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
9 https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
10
11 <!-- Enables the Spring MVC @Controller programming model -->
12 <annotation-driven />
13
14 <context:component-scan
15 base-package="com.journaldev.spring" />
16
17 <beans:bean id="jsonMessageConverter"
18 class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
19 <beans:bean id="xmlMessageConverter"
20 class="org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter" />
21
22 <beans:bean
23 class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
24 <beans:property name="messageConverters">
25 <beans:list>
26 <beans:ref bean="jsonMessageConverter" />
27 <beans:ref bean="xmlMessageConverter" />
28 </beans:list>
29 </beans:property>
30 </beans:bean>
31
32</beans:beans>
最重要的部分是jsonMessageConverter
和xmlMessageConverter
的豆子定义并设置在RequestMappingHandlerAdapter
的messageConverters
属性中。
春季控制班级
以下是我们的 Spring RestController 类实现。
1package com.journaldev.spring.controller;
2
3import java.util.List;
4
5import org.springframework.beans.factory.annotation.Autowired;
6import org.springframework.web.bind.annotation.DeleteMapping;
7import org.springframework.web.bind.annotation.GetMapping;
8import org.springframework.web.bind.annotation.PathVariable;
9import org.springframework.web.bind.annotation.PostMapping;
10import org.springframework.web.bind.annotation.RequestBody;
11import org.springframework.web.bind.annotation.RestController;
12
13import com.journaldev.spring.model.Employee;
14import com.journaldev.spring.repository.EmployeeRepository;
15
16@RestController
17public class EmployeeRestController {
18
19 @Autowired
20 private EmployeeRepository repository;
21
22 @GetMapping("/rest/employee/get/{id}")
23 public Employee getEmployeeByID(@PathVariable("id") int id) {
24 return repository.retrieve(id);
25 }
26
27 @GetMapping("/rest/employee/getAll")
28 //Returning is List is supported with JSON response only
29 //If you want XML, then add a wrapper class as Root XML element, for example EmployeeList
30 public List<Employee> getAllEmployees() {
31 return repository.getAll();
32 }
33
34 @PostMapping("/rest/employee/create")
35 public Employee createEmployee(@RequestBody Employee emp) {
36 repository.store(emp);
37 return emp;
38 }
39
40 @GetMapping("/rest/employee/search/{name}")
41 public Employee getEmployeeByName(@PathVariable("name") String name) {
42 return repository.search(name);
43 }
44
45 @DeleteMapping("/rest/employee/delete/{id}")
46 public Employee deleteEmployeeByID(@PathVariable("id") int id) {
47 return repository.delete(id);
48 }
49}
如果我们的方法是返回列表或数组,那么春天只会支持JSON响应,因为XML根元素不能匿名,但JSON可以。如果你想支持返回列表作为XML,那么你将不得不创建一个包装类来持有这个列表并返回它。我们预计员工对象作为某些方法的请求,春天将负责分析请求体并将其转换为员工对象为这些方法。
接受和内容类型请求标题
我们已经配置了我们的 REST 应用程序以与 XML 和 JSON 一起工作,所以它将如何知道请求是否为 XML 或 JSON. 如果答案应该以 JSON 或 XML 格式发送,这就是使用接受
和内容类型
请求标题的地方。 内容类型:在请求体中定义了内容类型,如果其值是应用程序/xml
,那么 Spring 将请求体视为 XML 文档。如果其值是应用程序/json
,那么请求体将被视为 JSON。
春季控制器测试
我们的应用程序已经准备好进行测试,我已经在Tomcat-9上部署了它,并与Postman进行测试。
春季 RestController 获得 JSON 响应
It's a simple GET request, the important point to note is the value of "Accept" header.
Spring RestController 获得 XML 响应
When we changed "Accept" header value to "application/xml", we are getting XML response.
春季控制器获取列表
Let's try to call the API to get list of employees. We are getting list of elements in JSON with anonymous root element.
Since XML doesn't support anonymous root element, we are getting exception message.
春天 转发 邮件
Spring RestController POST with JSON Request and Response Spring RestController POST with JSON Request Body
Spring RestController POST with JSON Request and XML Response
春季控制器删除
摘要
Spring RestController 帮助我们专注于业务逻辑,通过处理创建 REST Web Services API 的所有锅炉板材料。
您可以从我们的 GitHub 存储库下载完整的项目。