Spring: how to pass objects from filters to controllers

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

        }
    }
}

Why Don't you use a Bean with the @Scope('request')

@Component
@Scope(value="request", proxyMode= ScopedProxyMode.TARGET_CLASS)
class UserInfo {
   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

   private String password;
}

and then you can Autowireed this bean in both filter and controller to do setting and getting of data.

lifecycle of this UserInfo bean is only exisits within the request so once the http request is done then it terminates the instance as well


An addition to wcong's answer. Since Spring 4.3 after setting the attribute by using request.setAttribute(passKey, passValue);, you can access the attribute in your controller by simply annotating it with @RequestAttribute.

ex.

@RequestMapping("/")
public String index(@RequestAttribute passKey) {
    return (String) passKey;
}