簡體   English   中英

過濾 cookies 數組以獲取特定 cookie 並獲取 Java 中特定 cookie 的值

[英]Filter Array of cookies for a specific cookie and get value of a specific cookie in Java

我正在修復遺留模塊中的一些問題,並遇到了從請求 object 中獲取 cookies 數組的代碼,該請求可以返回 null。 代碼查找特定的 cookie,如果存在則返回 cookie 值,否則返回 null。 以下是現有代碼

final Cookie[] cookies = request.getCookies();
if (cookies != null) {
    for (int i = 0; i < cookies.length; i++) {
        final Cookie cookie = cookies[i];
        if ("random cookie".equals(cookie.getName())) {
            return cookie.getValue();
        }
    }
    return null;
}

我將它重構為這樣的東西

final Cookie[] cookies = request.getCookies();
if (cookies != null) {
    Optional<Cookie> cookie = Arrays.stream(cookies).
            filter(e -> "random cookie".equals(e.getName())).
            findAny();
    return cookie.isPresent() ? cookie.get().getValue() : null;
}
return null;

可以以更好的方式重構上述內容嗎?

最好讓該方法返回Optional<String> - 但如果你不能那么如何:

final Cookie[] maybeCookies = request.getCookies();
return Optional.ofNullable(maybeCookies)
    .flatMap(cookies -> Arrays.stream(cookies)
         //Find the cookie if we can.
         .filter(e->"random cookie".equals(cookie.getName()))
         .findAny()
    )
    //If we have a matching cookie, return its value.
    .map(e->e.getValue())
    //otherwise return null to retain original behaviour
    .orElse(null);

我會將其重構為返回Optional<String>的方法:

public Optional<String> getCookieValue(String name) {
   final Cookie[] cookies = request.getCookies();
   if(cookies == null) return Optional.empty();
   return Arrays.stream(cookies)
                .filter(e -> name.equals(e.getName()))
                .findAny().map(Cookie::getValue);
} 

那么這個方法的調用者將根據他們打算如何使用結果來執行任何這些操作:

getCookieValue("random cookie").ifPresent(e -> { ... });
getCookieValue("random cookie").orElse(null);
....
....

返回Optional<String>以避免處理無效性,並讓此方法的用戶決定在“無值情況”中做什么。 這對 API 等的用戶來說也更容易閱讀......

但是,如果您希望堅持使用當前的方法簽名,那么您至少可以將其改進為:

final Cookie[] cookies = request.getCookies();
if(cookies == null) return null; // avoids if blocks
return Arrays.stream(cookies)
             .filter(e -> "random cookie".equals(e.getName()))
             .findAny()
             .map(Cookie::getValue)
             .orElse(null);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM