You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Play Framework Java:Mock服务器中RoutingDSL获取请求头(Cookie)

How to Validate Request Cookies with Play Framework's RoutingDSL (Java)

Hey there! I’ve been working on setting up a mock server with Java Play Framework too, and ran into exactly the same problem—trying to use RoutingDSL to define routes and responses, but stuck on how to access request headers (specifically validating if the client sends the right cookies). After digging into the official docs, I figured out the solution and wanted to share it with you:

The Core Idea

RoutingDSL gives you access to the full Http.Request object either in the route handler logic, or via custom request matchers. This lets you pull out cookies and validate them exactly how you need.

Example 1: Validate Cookies in the Route Handler

If you want to check cookies while building your response, you can pass a lambda that accepts the Http.Request to routeTo():

import play.mvc.Http;
import play.mvc.Result;
import play.routing.RoutingDsl;
import play.routing.Router;

public class MockTestRouter {
    public Router buildMockRouter() {
        return RoutingDsl.fromComponents()
                .GET("/api/protected-endpoint")
                .routeTo(request -> {
                    // Fetch the target cookie from the request
                    Http.Cookie sessionCookie = request.cookies().get("SESSION_TOKEN");
                    
                    // Validate the cookie's presence and value
                    if (sessionCookie != null && "authorized_session_123".equals(sessionCookie.value())) {
                        return Results.ok("Success: Valid session cookie provided");
                    } else {
                        return Results.unauthorized("Error: Missing or invalid session cookie");
                    }
                })
                .build();
    }
}

Example 2: Validate Cookies During Route Matching

If you want to restrict a route to only match requests with valid cookies (instead of handling the validation in the response logic), you can create a custom RequestMatcher:

import play.mvc.Http;
import play.routing.RoutingDsl;
import play.routing.Router;
import play.routing.RequestMatcher;

public class MockTestRouter {
    public Router buildMockRouter() {
        // Define a matcher that checks for a valid session cookie
        RequestMatcher hasValidSession = request -> {
            Http.Cookie sessionCookie = request.cookies().get("SESSION_TOKEN");
            return sessionCookie != null && "authorized_session_123".equals(sessionCookie.value());
        };
        
        return RoutingDsl.fromComponents()
                // Route only matches if the cookie is valid
                .GET("/api/protected-endpoint")
                .matching(hasValidSession)
                .routeTo(() -> Results.ok("Success: Valid session"))
                // Fallback route for invalid/missing cookies
                .GET("/api/protected-endpoint")
                .routeTo(() -> Results.unauthorized("Error: Invalid session"))
                .build();
    }
}

Either way, you’re leveraging the Http.Request object that Play provides in RoutingDSL to access and validate cookies. This approach works for checking any request headers too, not just cookies!

内容的提问来源于stack exchange,提问作者Dusan Kostic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:18:05