刷新JSF 2.0中的托管会话Bean

3
在我将一些数据提交到数据库后,我希望我的会话bean自动刷新以反映最近提交的数据。当使用JSF 2.0中的托管会话bean时,如何实现这一点?
目前,为了清除并重新加载会话,我必须重新启动Web服务器。
1个回答

6

有两种方法:

  1. Put them in the view scope instead. Storing view-specific data sessionwide is a waste. If you have a performance concern, you should concentrate on implementing connection pooling, DB-level pagination and/or caching in the persistence layer (JPA2 for example supports second level caching).

    @ManagedBean
    @ViewScoped
    public class FooBean {
        // ...
    }
    

  2. Add a public load() method so that it can be invoked from the action method (if necessary, from another bean).

    @ManagedBean
    @SessionScoped
    public class FooBean {
    
        private List<Foo> foos;
    
        @EJB
        private FooService fooService;
    
        @PostConstruct
        public void load() {
            foos = fooService.list();
        }
    
        // ...
    }
    

    which can be invoked in action method inside the same bean (if you submit the form to the very same managed bean of course):

        public void submit() {
            fooService.save(foos);
            load();
        }
    

    or from an action method in another bean (for the case that your managed bean design is a bit off from usual):

        @ManagedProperty("#{fooBean}")
        private FooBean fooBean;
    
        public void submit() {
            fooService.save(foos);
            fooBean.load();
        }
    

    This of course only affects the current session. If you'd like to affect other sessions as well, you should really consider putting them in the view scope instead, as suggested in the 1st way.

参见:


实际上这个解决方案是可行的,但我发现当您在3个不同的JSF页面中使用相同的bean时,bean的值会在页面之间丢失。我需要保留这些值。 - D. Bermudez
将Bean的作用域设置为视图作用域,就像第一种方式建议的那样。它显然不应该是一个会话作用域的Bean。另请参阅:托管Bean作用域 - BalusC
我明白了,如果我希望在会话中保留它们的值并在其他页面中使用它们,则所有我的托管 bean 应该是 ViewScoped。 - D. Bermudez
不,如果您想要在每个视图中使用同一个bean,则它们应该是视图作用域。这样,每个浏览器选项卡/窗口都将有自己的bean实例。它们在会话期间彼此之间不共享。为此,您需要一个会话作用域的bean。 - BalusC
啊好的。谢谢Balus C...我觉得现在我开始了解不同类型的作用域了。 - D. Bermudez
@BalusC,你太牛了!为什么在JSF方面如此出色?无论我走到哪里,都能看到你的名字... - stuckedoverflow

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接