【问题标题】:spring clear session scope bean春季清除会话范围bean
【发布时间】:2019-09-13 12:25:05
【问题描述】:

我创建了一个会话范围的 bean,如下所示:

@Bean
@Scope(
    value = WebApplicationContext.SCOPE_SESSION,
    proxyMode = ScopedProxyMode.TARGET_CLASS)
public TodoList todos() {
    return new TodoList();
}

我已将 bean 添加为模型属性,并且可以跨多个页面显示 bean。

@GetMapping("/todos.html")
public String list(Model model) {
    model.addAttribute("todos", todos);
    return "scopedproxytodos";
}

但我不确定如何清除会话中的属性。

@PostMapping("/end")
public ModelAndView endSession(SessionStatus sessionStatus, Model model) {
    model.addAttribute("todos", new TodoList());
    sessionStatus.setComplete();
    return new ModelAndView("redirect:/");
}

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    我已将 bean 添加为模型属性,并且可以显示 跨多个页面的bean:

    ...

    `model.addAttribute("todos", todos);`
    

    ...

    不是真的。这只会在当前视图中添加属性。

    要实现这一点,您应该使用 @SessionScope 注释您的 TodoList 类,例如:

    @SessionScope
    @Component
    public class TodoList {
        // ...
    }
    

    然后使用@SessionAttributes 注释您需要为todos 提供对话范围的控制器,并使用@ModelAttribute 注入它。未经测试,但类似:

    @Controller
    @SessionAttributes("todos")
    public class FooController { 
    
      @GetMapping("/todos.html")
      public String list(@ModelAttribute TodoList todos) {
        // set the todos value
        return "scopedproxytodos";
      }
    
    }
    

    您可以在任何其他带有 @SessionAttributes("todos") 注释的控制器中使用它。

    要删除当前会话会话的todos,请像以前一样使用status.setComplete()。
    在您的情况下,您可以删除它:

    @PostMapping("/end")
    public ModelAndView endSession(SessionStatus sessionStatus, Model model) {
        sessionStatus.setComplete();
        return new ModelAndView("redirect:/");
    }
    

    并让具有会话范围的控制器根据需要重新初始化它(FooController 实际上是这样做的)。
    另一种方法是重新初始化它而不是删除它。
    例如:

    @PostMapping("/end")
    public ModelAndView endSession(@ModelAttribute TodoList todos) {
        todos.clear();
        return new ModelAndView("redirect:/");
    }
    

    此方案的优势:

    • 简洁/简洁
    • 不需要为每个会话创建 bean。就开销而言,Bean 比存储在会话中的值更昂贵。

    More information here about that way of manipulate conversational attributes.


    SessionStatus 类管理 Spring 会话的属性:

    可以注入处理程序方法的简单接口,允许 他们表示他们的会话处理已完成。处理程序 然后调用者可以跟进适当的清理,例如会话的 在此处理程序的过程中隐式创建的属性 处理

    这意味着它清除了存储在 Spring 处理程序会话中的属性(与经典的 http 会话不同),而不是存储在 http 请求中的属性,实际上您没有在 spring 会话属性中添加任何内容。 所以这是没用的。

    【讨论】:

    • 您好,感谢您的详细回复。我很感激。如果我错了,请纠正我。 sessionattributes 是另一种方法。但是仍然如何清除该会话范围的 bean?
    • 不客气。 Spring Beans 和 Spring 属性可能都有一个作用域会话,但它们是两个不同的东西。 spring bean todos 不会在 http 会话没有被清除时被清除。这就是为什么你不应该将它用于会话需求。
    猜你喜欢
    • 2016-08-05
    • 1970-01-01
    • 2017-03-18
    • 2013-11-29
    • 2013-02-06
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    相关资源
    最近更新 更多