Spring: how to pass objects from filters to controllers

前端 未结 5 1382
被撕碎了的回忆
被撕碎了的回忆 2021-01-02 05:19

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 \"cen

5条回答
  •  爱一瞬间的悲伤
    2021-01-02 05:34

    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() {
    
            }
        }
    }
    

提交回复
热议问题