Is there a static way to get the HttpServletRequest of the current request

后端 未结 4 2027
太阳男子
太阳男子 2020-12-13 18:04

I am using Spring annotations, I can pass the HttpRequestContext from the Controller to the Service.

I am looking for a static way or any better soluti

4条回答
  •  难免孤独
    2020-12-13 18:38

    In response to @andrebrait comments above "Or the Java 8 way", the methods are present on the ServletRequestAttributes.class

        public static Optional getCurrentHttpRequest() {
            return
                Optional.ofNullable(
                    RequestContextHolder.getRequestAttributes()
                )
                .filter(ServletRequestAttributes.class::isInstance)
                .map(ServletRequestAttributes.class::cast)
                .map(ServletRequestAttributes::getRequest);
        }
    

提交回复
热议问题