Spring REST – HTTP OPTIONS 请求处理器示例
原文: https://howtodoinjava.com/spring-restful/http-options-request-handler/
通过为RequestMethod.OPTIONS
添加特定的处理器方法,学习在 Spring webmvc 应用程序中处理特定于 REST 资源的 HTTP 选项请求。
1. HTTP OPTIONS 方法
HTTP OPTIONS 方法用于描述目标资源的通信选项。 此方法允许客户端确定与资源相关联的选项和/或要求,或者服务器的功能,而无需暗示资源操作或启动资源检索。
- 如果 Request-URI 是星号(
*
),则 OPTIONS 请求通常适用于服务器而不是特定资源。 - 如果 Request-URI 不是星号,则 OPTIONS 请求仅适用于与该资源进行通信时可用的选项。
- 此方法的响应是不可缓存。
2. 将选项处理器方法添加到 REST 控制器
下一步是添加处理器方法以处理 OPTIONS 请求。
EmployeeRESTController.java
@RestController
@RequestMapping(value = "/employee-management", produces = { MediaType.APPLICATION_JSON_VALUE })
public class EmployeeRESTController
{
@RequestMapping(value="/employees", method = RequestMethod.OPTIONS)
ResponseEntity<?> collectionOptions()
{
return ResponseEntity
.ok()
.allow(HttpMethod.GET, HttpMethod.POST, HttpMethod.OPTIONS)
.build();
}
@RequestMapping(value="/employees/{id}", method = RequestMethod.OPTIONS)
ResponseEntity<?> singularOptions()
{
return ResponseEntity
.ok()
.allow(HttpMethod.GET, HttpMethod.DELETE, HttpMethod.PUT, HttpMethod.OPTIONS)
.build();
}
//Other APIs
}
3. 演示
要测试 OPTIONS 请求是否被正确处理,请在任何 REST 客户端插件或 SoapUI 中进行测试。
点击 URL:HTTP 选项
http://localhost:8080/api/rest/employee-management/employees/1
在 cURL 中,我们可以通过点击以下 URL 进行测试。
Option 验证响应 - 1
curl -i -X OPTIONS http://localhost:8080/SpringRestExample/api/rest/employee-management/employees/
Response:
#status# HTTP/1.1 200 OK
Server Apache-Coyote/1.1
Content-Length 0
Date Thu, 02 May 2019 10:41:02 GMT
Allow GET,POST,OPTIONS
Option 验证响应 - 2
curl -i -X OPTIONS http://localhost:8080/SpringRestExample/api/rest/employee-management/employees/1
Response:
#status# HTTP/1.1 200 OK
Server Apache-Coyote/1.1
Content-Length 0
Date Thu, 02 May 2019 10:43:15 GMT
Allow GET,DELETE,PUT,OPTIONS
学习愉快!