Spring: how to pass objects from filters to controllers

前端 未结 5 1405
被撕碎了的回忆
被撕碎了的回忆 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:36

    One way I've seen this done is to wrap the HttpServletRequest object with your own implementation that is aware of the original and your temporary object. The advantage to this is that it's limited to the request scope and isn't stored in the thread or session. So something like this:

    public class MyServletRequest extends HttpServletRequestWrapper {
      private MyObject obj;
      public MyServletRequest(HttpServletRequest request){
        super(request);
      }
      //set your object etc
    }
    

    Then in your servlet:

    public void doGet(HttpServletRequest req, HttpServletResponse resp){
       MyServletRequest myRequest = (MyServletRequest)req;
       //now you can access your custom objects
    }
    

提交回复
热议问题