Spring:如何将对象从过滤器传递到控制器 [英] Spring: how to pass objects from filters to controllers

查看:320
本文介绍了Spring:如何将对象从过滤器传递到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加一个过滤器来创建一个对象,然后该对象将在Spring Boot应用程序的控制器内部使用.

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.

这个想法是将Filter用作此对象的集中式"生成器-特定于请求,仅在控制器中有用. 我尝试使用HttpServletRequest request.getSession().setAttribute方法:我可以在控制器中访问我的对象,但是(显然)它将被添加到会话中.

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?

推荐答案

您可以使用 ServletRequest.setAttribute(String name,Object o);

例如

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

        }
    }
}

这篇关于Spring:如何将对象从过滤器传递到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆