服务器如何将异步更改推送到JSF创建的HTML页面?

Roh*_*nga 19 jsf asynchronous push

当我们创建JSF页面时,客户端请求允许使用Java代码和HTML的组合动态生成HTML.我们可以使用JSF框架在HTML页面中引入钩子,允许服务器基于稍后在服务器上发生的异步事件来更新HTML页面,通常是通过不同的线程吗?

Bal*_*usC 29

JSF 2.3+

你可以使用@Push<f:websocket>为此.下面是一个启动示例,它根据后端触发的应用程序作用域事件更新数据表.

<h:dataTable id="notifications" value="#{bean.notifications}" var="notification">
    <h:column>#{notification.message}</h:column>
</h:dataTable>

<h:form>
    <f:websocket channel="push">
        <f:ajax event="updateNotifications" render=":notifications" />
    </f:websocket>
</h:form>
Run Code Online (Sandbox Code Playgroud)

@Named @ApplicationScoped
public class Bean {

    private List<Notification> notifications;

    @Inject
    private NotificationService service;

    @Inject @Push
    private PushContext push;

    @PostConstruct
    public void load() {
        notifications = service.list();
    }

    public void onNewNotification(@Observes Notification newNotification) {
        notifications.add(0, newNotification);
        push.send("updateNotifications");
    }

    public List<Notification> getNotifications() {
        return notifications;
    }

}
Run Code Online (Sandbox Code Playgroud)

@Stateless
public class NotificationService {

    @Inject
    private EntityManager entityManager;

    @Inject
    private BeanManager beanManager;

    public void create(String message) {
        Notification newNotification = new Notification();
        newNotification.setMessage(message);
        entityManager.persist(newNotification);
        beanManager.fireEvent(newNotification);
    }

    public List<Notification> list() {
        return entityManager
            .createNamedQuery("Notification.list", Notification.class)
            .getResultList();
    }

}
Run Code Online (Sandbox Code Playgroud)

JSF 2.2-

如果您还没有使用JSF 2.3,那么您需要前往第三方JSF库.

注意到它应该是<o:socket>JSF 2.3的基础<f:websocket>.所以,如果你发现了很多相似之处,那就是正确的.

PrimeFaces 在引擎盖下使用Atmosphere(没有Maven设置很麻烦).Atmosphere支持回退到SSE和长轮询的websockets.ICEfaces基于古老的长轮询技术.所有这些都没有实现本机JSR356 WebSocket API,后者仅在Java EE 7中引入.

OmniFaces使用本机JSR356 WebSocket API(所有Java EE 7服务器和Tomcat 7.0.27+都支持).因此,设置和使用也是最简单的(一个JAR,一个上下文参数,一个标记和一个注释).它只需要CDI(不难在Tomcat安装),但它使您甚至可以从非JSF工件上推送(例如a @WebServlet).对于安全性和JSF视图状态保持原因,它只支持单向推送(服务器到客户端),而不是相反.为此,您可以通常的方式继续使用JSF ajax.JSF 2.3 <f:websocket>主要基于OmniFaces <o:socket>,因此你会发现它们的API(JSF - OmniFaces)有很多相似之处.

或者,您也可以使用轮询而不是推送.几乎每个ajax感知的JSF组件库都有一个<xxx:poll>组件,比如PrimeFaces <p:poll>.这允许您每隔X秒向服务器发送一个ajax请求,并在必要时更新内容.它只比推送效率低.

也可以看看:


归档时间:

查看次数:

15021 次

最近记录:

7 年,8 月 前