Search code examples
springspring-boot

Spring: how to pass objects from filters to controllers


I'm trying to add a Filter that creates an object that is then to be used inside a controller in a Spring Boot application.

The idea is to use the Filter as a "centralized" generator of this object - that is request-specific and useful only in a controller. I've tried to use the HttpServletRequest request.getSession().setAttribute method: I can access my object in the controller, but then it will be (clearly) added to the session.

Are the Filters the right way to do so? If yes, where can I keep the temporary object generated by the filter to be used by the controllers?


Solution

  • you can use ServletRequest.setAttribute(String name, Object o);

    for example

    @RestController
    @EnableAutoConfiguration
    public class App {
    
        @RequestMapping("/")
        public String index(HttpServletRequest httpServletRequest) {
            return (String) httpServletRequest.getAttribute(MyFilter.passKey);
        }
    
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    
        @Component
        public static class MyFilter implements Filter {
    
            public static String passKey = "passKey";
    
            private static String passValue = "hello world";
    
            @Override
            public void init(FilterConfig filterConfig) throws ServletException {
    
            }
    
            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                    throws IOException, ServletException {
                request.setAttribute(passKey, passValue);
                chain.doFilter(request, response);
            }
    
            @Override
            public void destroy() {
    
            }
        }
    }