introduction
In modern web development, HTTP request headers are one of the important ways to pass information between clients and servers. Common scenarios include:
- pass
Cookie
Pass session information. - pass
Authorization
Header pass authentication token.
This article will introduce in detail how to extract the request header in the Java backend (taking Spring Boot as an example)Cookie
andToken
, and provide complete code examples and optimization suggestions.
1. Background
1.1 What is an HTTP request header?
HTTP request headers are additional information sent to the server by the client (such as a browser) and are used to pass metadata. Common request headers include:
-
Cookie
: Used to pass the session information stored by the client. -
Authorization
: Used to pass authentication information, such as JWT Token.
1.2 Why do I need to extract the request header?
In back-end development, extracting information in request headers is a common requirement. For example:
-
Authentication:from
Authorization
Extract the token from the header to verify the user's identity. -
Session Management:from
Cookie
Extract the session ID from to maintain the user session status. - Data delivery: Pass additional business data through custom request headers.
2. Use Spring Boot to extract the request header
Spring Boot provides multiple ways to handle HTTP request headers. Here are a few common methods:
2.1 Annotation using @RequestHeader
@RequestHeader
Annotations can directly bind the values in the request header to the parameters of the method.
Sample code
import ; import ; import ; @RestController public class HeaderController { @GetMapping("/example") public String getHeaders( @RequestHeader("Cookie") String cookie, // Extract cookies @RequestHeader("Authorization") String token // Extract Token ) { return "Cookie: " + cookie + ", Token: " + token; } }
illustrate
-
@RequestHeader("Cookie")
: Extract the request headerCookie
。 -
@RequestHeader("Authorization")
: Extract the request headerToken
(usually placedAuthorization
In the head).
Things to note
- If there is no specified field in the request header, Spring will throw
MissingRequestHeaderException
. Can be passedrequired = false
Set as optional parameters:
@RequestHeader(value = "Cookie", required = false) String cookie
2.2 Using HttpServletRequest
passHttpServletRequest
Object, you can manually get the value in the request header.
Sample code
import ; import ; import ; @RestController public class HeaderController { @GetMapping("/example") public String getHeaders(HttpServletRequest request) { String cookie = ("Cookie"); // Extract cookies String token = ("Authorization"); // Extract Token return "Cookie: " + cookie + ", Token: " + token; } }
illustrate
-
("Cookie")
: ObtainCookie
The value of the header. -
("Authorization")
: ObtainAuthorization
The value of the header.
advantage
- More flexible and suitable for scenarios where request headers need to be processed dynamically.
2.3 Annotation using @CookieValue
ifCookie
It is passed in the form of key-value pairs (e.g.Cookie: name=value
), can be used@CookieValue
Annotation extracts specificCookie
Value.
Sample code
import ; import ; import ; @RestController public class HeaderController { @GetMapping("/example") public String getCookie( @CookieValue("sessionId") String sessionId // Extract specific cookie values ) { return "Session ID: " + sessionId; } }
illustrate
-
@CookieValue("sessionId")
: Extracted name assessionId
ofCookie
Value.
Things to note
- if
Cookie
Not exists, Spring will throwMissingRequestCookieException
. Can be passedrequired = false
Set as optional parameters:
@CookieValue(value = "sessionId", required = false) String sessionId
3. Common ways to extract tokens
Token
Usually placedAuthorization
In the header, the format isBearer <token>
. We need to extractBearer
The latter part.
3.1 Use @RequestHeader and string processing
import ; import ; import ; @RestController public class HeaderController { @GetMapping("/example") public String getToken( @RequestHeader("Authorization") String authHeader // Extract Authorization header ) { if (authHeader != null && ("Bearer ")) { String token = (7); // Extract the part behind Bearer return "Token: " + token; } else { return "Invalid Authorization header"; } } }
illustrate
-
("Bearer ")
:examineAuthorization
Is the head ofBearer
The beginning. -
(7)
: ExtractBearer
The latterToken
。
3.2 Using HttpServletRequest and string processing
import ; import ; import ; @RestController public class HeaderController { @GetMapping("/example") public String getToken(HttpServletRequest request) { String authHeader = ("Authorization"); // Extract Authorization header if (authHeader != null && ("Bearer ")) { String token = (7); // Extract the part behind Bearer return "Token: " + token; } else { return "Invalid Authorization header"; } } }
4. Comprehensive example
The following is a comprehensive example, extractCookie
andToken
, and return the processing result:
import ; import ; import ; import ; @RestController public class HeaderController { @GetMapping("/example") public String getHeaders( @RequestHeader(value = "Cookie", required = false) String cookie, // Extract cookies @RequestHeader(value = "Authorization", required = false) String authHeader // Extract Authorization header ) { // Handle cookies String cookieInfo = (cookie != null) ? "Cookie: " + cookie : "No Cookie provided"; // Handle Token String tokenInfo; if (authHeader != null && ("Bearer ")) { String token = (7); // Extract the part behind Bearer tokenInfo = "Token: " + token; } else { tokenInfo = "Invalid or missing Authorization header"; } return cookieInfo + ", " + tokenInfo; } }
5. Test interface
You can use Postman or curl to test the interface:
5.1 Request Example
curl -X GET http://localhost:8080/example \ -H "Cookie: sessionId=abc123" \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
5.2 Response Example
{ "Cookie": "sessionId=abc123", "Token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." }
6. Summary
Extract the request header in the Java backend (Spring Boot)Cookie
andToken
There are many ways:
-
use
@RequestHeader
Note: Suitable for directly binding request headers to method parameters. -
use
HttpServletRequest
: Suitable for scenarios where request headers need to be processed dynamically. -
use
@CookieValue
Note: Suitable for extracting specificCookie
Value.
ForToken
, usually need toAuthorization
Extract from headerBearer
The latter part. Through reasonable exception handling and parameter verification, the robustness and maintainability of the code can be ensured.
The above is the detailed content of the method of extracting cookies and tokens in the request header in the Java backend interface. For more information about extracting cookies and tokens in the Java backend interface, please follow my other related articles!