Spring: how to pass objects from filters to controllers

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

    I dont know actually what is the scenario but If you really want to create an object in a filter and then use it somewhere in the code then you may use ThreadLocal class to do so.

    To get know how this work see the most voted answer from that question Purpose of ThreadLocal?

    In general using ThreadLocal you will be able to create a class that can store objects available ONLY for the current thread.

    Sometimes for optimization reasons the same thread can be used to serve subsequent request as well so it will be nice to clean the threadLocal value after the request is processed.

    class MyObjectStorage {
      static private ThreadLocal threadLocal = new ThreadLocal();
    
      static ThreadLocal getThreadLocal() {
        return threadLocal;
      }
    }
    

    in the filter

    MyObjectStorage.getThreadLocal().set(myObject);
    

    and in the Controller

    MyObjectStorage.getThreadLocal().get();
    

    Instead of filter you can use also @ControllerAdvice and pass objects to specified Controllers by using model.

    @ControllerAdvice(assignableTypes={MyController.class})
    class AddMyObjectAdvice {
    
        // if you need request parameters
        private @Inject HttpServletRequest request; 
    
        @ModelAttribute
        public void addAttributes(Model model) {
            model.addAttribute("myObject", myObject);
        }
    }
    
    
    @Controller
    public class MyController{
    
       @RequestMapping(value = "/anyMethod", method = RequestMethod.POST)
       public String anyMethod(Model model) {
          MyObjecte myObject = model.getAttribute("myObject");
    
          return "result";
       }
    }
    

提交回复
热议问题