SoFunction
Updated on 2025-04-05

Methods to extract cookies and tokens in request headers in Java backend interface

introduction

In modern web development, HTTP request headers are one of the important ways to pass information between clients and servers. Common scenarios include:

  • passCookiePass session information.
  • passAuthorizationHeader 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)CookieandToken, 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:fromAuthorizationExtract the token from the header to verify the user's identity.
  • Session Management:fromCookieExtract 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

@RequestHeaderAnnotations 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 placedAuthorizationIn the head).

Things to note

  • If there is no specified field in the request header, Spring will throwMissingRequestHeaderException. Can be passedrequired = falseSet as optional parameters:
@RequestHeader(value = "Cookie", required = false) String cookie

2.2 Using HttpServletRequest

passHttpServletRequestObject, 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"): ObtainCookieThe value of the header.
  • ("Authorization"): ObtainAuthorizationThe value of the header.

advantage

  • More flexible and suitable for scenarios where request headers need to be processed dynamically.

2.3 Annotation using @CookieValue

ifCookieIt is passed in the form of key-value pairs (e.g.Cookie: name=value), can be used@CookieValueAnnotation extracts specificCookieValue.

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 assessionIdofCookieValue.

Things to note

  • ifCookieNot exists, Spring will throwMissingRequestCookieException. Can be passedrequired = falseSet as optional parameters:
@CookieValue(value = "sessionId", required = false) String sessionId

3. Common ways to extract tokens

TokenUsually placedAuthorizationIn the header, the format isBearer <token>. We need to extractBearerThe 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 &amp;&amp; ("Bearer ")) {
            String token = (7); // Extract the part behind Bearer            return "Token: " + token;
        } else {
            return "Invalid Authorization header";
        }
    }
}

illustrate

  • ("Bearer "):examineAuthorizationIs the head ofBearerThe beginning.
  • (7): ExtractBearerThe 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 &amp;&amp; ("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, extractCookieandToken, 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 &amp;&amp; ("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)CookieandTokenThere are many ways:

  1. use@RequestHeaderNote: Suitable for directly binding request headers to method parameters.
  2. useHttpServletRequest: Suitable for scenarios where request headers need to be processed dynamically.
  3. use@CookieValueNote: Suitable for extracting specificCookieValue.

ForToken, usually need toAuthorizationExtract from headerBearerThe 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!