LoginSignup
3
3

More than 5 years have passed since last update.

HttpServletRequestのヘッダをMapで使いやすくする

Posted at
  • クライアントからのリクエストヘッダの名称はjavax.servlet.http.HttpServletRequest#getHeaderNamesで取得できる。
    • ところが戻り値がEnumeration<String>なので、Java8の時代には利用し難い。
    • Streamを利用して、ヘッダ名をキーに持ち、値をリストで持つMapに変換して使いやすくする。
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class RequestUtils {

    public static Map<String, List<String>> getHeaders(HttpServletRequest request) {
        return Collections.list(request.getHeaderNames()).stream()
                .collect(Collectors.toMap(
                        headerName -> headerName,
                        headerName -> Collections.list(request.getHeaders(headerName))));
    }

}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3