Spring RestController

Spring RestController注解是一个方便的注解,本身带有@Controller@ResponseBody的注解。此注解应用于类,将其标记为请求处理程序。Spring RestController注解用于使用Spring MVC创建RESTful Web服务。Spring RestController负责将请求数据映射到定义的请求处理程序方法。一旦从处理程序方法生成了响应主体,它会将其转换为JSON或XML响应。

Spring RestController示例

让我们看看如何轻松地使用RestController在Spring中创建REST Web服务。我们将重用Spring Repository的实现并创建一个RESTful Web服务。我们将创建一个独立的Web应用程序,而不在此使用Spring Boot。我们还将暴露我们的API以支持JSON和XML在请求和响应中。下图显示了我们最终的项目结构。模型和存储库类已在Spring Repository教程中提供。我们将在这里更加关注RestController的实现。

Spring RestController Maven Dependencies

讓我們來看看創建 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 Context 檔案。

<?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>

最重要的部分是在 RequestMappingHandlerAdaptermessageConverters 屬性中定義並設置的 jsonMessageConverterxmlMessageConverter beans。這就是告訴 Spring 我們希望我們的應用程式支援 JSON 和 XML,並且這些是要用於轉換的 beans。

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 格式的列表,那麼您將不得不創建一個包裹類來保存此列表並返回它。在某些方法中,我們期望作為請求的員工對象,Spring 會負責解析請求主體並將其轉換為這些方法的員工對象。同樣,我們將員工對象作為響應主體返回,Spring 將負責將其轉換為 JSON/XML 響應。

接受和 Content-Type 請求標頭

我們已經配置我們的 REST 應用程序可以使用 XML 和 JSON 進行工作。那麼它如何知道請求是 XML 還是 JSON。如果響應應該以 JSON 或 XML 格式發送。這就是 AcceptContent-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 發布

Spring RestController 發布並帶有 JSON 請求和回應 Spring RestController 發布並帶有 JSON 請求主體 Spring RestController 發布並帶有 JSON 請求和 XML 回應

Spring RestController 刪除

摘要

Spring RestController通過處理創建REST Web服務API的所有樣板內容,幫助我們專注於業務邏輯。

您可以從我們的GitHub存儲庫下載完整的項目。

Source:
https://www.digitalocean.com/community/tutorials/spring-restcontroller