Spring Controller获取请求Origin、JSON请求体及POST返回规范咨询
Hey there! Let's tackle your two questions about building a Spring REST API—super common scenarios when working with POST requests, so I've got you covered.
Unlike the request body which uses @RequestBody, there's no dedicated annotation for the Origin header specifically, but Spring gives you a straightforward way to grab it with the @RequestHeader annotation.
Here's a quick example of how to use it alongside your request body:
@RestController @RequestMapping("/api/your-resource") public class YourController { @PostMapping public ResponseEntity<?> handlePostRequest( // Extract JSON request body into your custom DTO @RequestBody YourRequestDto requestBody, // Extract the Origin header (mark as optional since some requests might not send it) @RequestHeader(value = "Origin", required = false) String origin) { // Now you can use the 'origin' string (e.g., validate CORS rules, log the source, etc.) if (origin != null) { System.out.println("Request originated from: " + origin); } // Your business logic goes here... return ResponseEntity.ok().build(); } }
A quick tip: setting required = false is smart because not all HTTP clients will send the Origin header (same-origin requests, for example, might omit it depending on the client). If you're certain the header will always be present, you can skip that parameter.
In Spring, the most flexible and widely recommended option is ResponseEntity<T>. It lets you control every part of the HTTP response: status code, headers, and the response body. Here are the common scenarios you'll encounter:
When creating a new resource (standard REST practice): Return a
201 Createdstatus, include the URI of the new resource in theLocationheader, and optionally return the created resource in the body. Example:@PostMapping public ResponseEntity<YourResponseDto> createResource(@RequestBody YourRequestDto requestBody) { YourResponseDto createdResource = yourService.createResource(requestBody); URI resourceUri = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}") .buildAndExpand(createdResource.getId()) .toUri(); return ResponseEntity.created(resourceUri).body(createdResource); }When the operation succeeds but doesn't need to return data: Use
204 No Content(no response body required):@PostMapping("/process") public ResponseEntity<Void> processData(@RequestBody YourRequestDto requestBody) { yourService.process(requestBody); return ResponseEntity.noContent().build(); }When you want a standardized response structure: Create a generic API response DTO to keep your API responses consistent. For example:
public class ApiResponse<T> { private int statusCode; private String message; private T data; // Constructor, getters, setters }Then return it with the appropriate status code:
@PostMapping public ResponseEntity<ApiResponse<YourResponseDto>> handleRequest(@RequestBody YourRequestDto requestBody) { YourResponseDto result = yourService.doSomething(requestBody); ApiResponse<YourResponseDto> response = new ApiResponse<>(200, "Operation successful", result); return ResponseEntity.ok(response); }
Avoid returning raw objects directly (without wrapping in ResponseEntity)—this robs you of control over HTTP status codes and headers, making your API less predictable for clients.
内容的提问来源于stack exchange,提问作者Ayane

