How to access HttpServletResponse in Spring Component?

Viewed 1824

I have a spring-boot app with swagger code generator. Since the controllers are autogenerated from swagger yaml I don't think I can modify the controllers to access the HttpServletResponse.

Is there a way to access the HttpServletResponse from a class annotated with @Component?

I am trying to access the HttpServletResponse instance in order to set a cookie.

2 Answers

If you don't want to touch the controller at all would be to make your bean a spring filter bean. This article here gives you details how to declare such bean. Once declare you need to bind it to url pointing to your controller method.

https://www.baeldung.com/spring-boot-add-filter

It depends on What your final goal is.

Spring provides static class (ServletRequestAttributes) that you can use to access request/response from any place in the application:

public void method() {
        ServletRequestAttributes ra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ra != null) {
            HttpServletRequest request = ra.getRequest();
            HttpServletResponse response = ra.getResponse();
        }
    }

ra.getRequest() will return null if request has already been processed

Related