The <o:sse> is an UIComponent which opens an one-way (server to client) SSE (Server-Sent Events) based push connection in client
side which can be reached from server side via PushContext interface injected in any CDI/container managed artifact via
@Push(type=SSE) annotation.
All servlet filters mapped on /* must have @WebFilter(asyncSupported=true) or web.xml for SSE
to work. In case that's not possible for your filter (e.g because it relies on some request/thread-specific state after invoking chain.doFilter()
such as DB connection, locked/shared resource, ThreadLocal, etc), then you'll need to map it on a more specific URL-pattern excluding
and create yet another filter on /* which forwards to that filter when the request path does not match
.
The server (and proxy, if any) must also support HTTP/2 and have it enabled. Otherwise it will fall back to HTTP/1.1 which limits concurrent connections per
origin (e.g. Chrome limits to 6). In such case, multiple SSE connections across multiple tabs may hit this limit and queue further HTTP requests (including
Ajax requests!), which has the consequence that will simply stop working. With HTTP/2, SSE streams are multiplexed over a single TCP
connection.
Both <o:sse> and <o:socket> provide one-way (server to client) push. The table below summarizes the key differences to
help you choose the right transport.
SSE (<o:sse>) |
WebSocket (<o:socket>) |
|
|---|---|---|
| Transport | Plain HTTP | WebSocket protocol upgrade |
| Dependencies | None (async servlet) | Requires jakarta.websocket |
| Proxy/CDN/firewall | Works through HTTP infrastructure | May be blocked by proxies or corporate firewalls |
| Reconnect | Built-in (EventSource API) |
Manual (with cumulative backoff) |
| HTTP/2 multiplexing | Yes (shares TCP connection) | No (separate TCP connection) |
| Connection limit | Per origin without HTTP/2 | Not affected (protocol upgrade) |
| CDI events | SseEvent on open/close/switch |
SocketEvent on open/close/switch |
| Dynamic connect/disconnect | Not available | connected attribute |
When to prefer SSE: for typical unidirectional push use cases (notifications, live updates, dashboards) where HTTP infrastructure compatibility and simplicity are important. SSE is the simpler and more robust choice for most server-to-client push scenarios.
When to prefer WebSocket: when you need dynamic connect/disconnect via the connected attribute, or when your server does not support HTTP/2.
No explicit configuration is needed. The SSE endpoint is automatically registered during application startup when at least one
@Push(type=SSE) qualified injection point is detected.
Declare <o:sse> tag in the Faces view with at least a channel name and an
onmessage JavaScript listener function. The channel name may not be an EL expression and it may only contain alphanumeric
characters, hyphens, underscores and periods.
Here's an example which refers an existing JavaScript listener function (do not include the parentheses!).
<o:sse channel="someChannel" onmessage="sseListener" />
function sseListener(message, channel, event) {
console.log(message);
}
Here's an example which declares an inline JavaScript listener function.
<o:sse channel="someChannel" onmessage="function(message) { console.log(message); }" />
The onmessage JavaScript listener function will be invoked with three arguments:
message: the push message as JSON object.channel: the channel name, useful in case you intend to have a global listener.event: the raw
MessageEvent instance, useful in case you intend to inspect it.
The SSE connection is automatically established when the page loads and will auto-reconnect when the connection is lost due to e.g. a network error or server
restart. This is a built-in feature of the browser's EventSource API.
The SSE connection will be implicitly closed once the document is unloaded (e.g. navigating away, close of browser window/tab, etc).
In order to successfully reconnect after a server restart, or when switching to a new server node, you need to ensure that session persistence is enabled on the server.
In WAR side, you can inject PushContext via @Push(type=SSE) annotation on the
given channel name in any CDI/container managed artifact such as @Named, @WebServlet, etc wherever you'd like to send a
push message and then invoke PushContext#send(Object) with any Java object representing the push message.
@Inject
@Push(type = SSE)
private PushContext someChannel;
public void sendMessage(Object message) {
someChannel.send(message);
}
By default the name of the channel is taken from the name of the variable into which injection takes place. The channel name can be optionally specified via
the channel attribute. The example below injects the push context for channel name foo into a variable named bar.
@Inject @Push(type = SSE, channel = "foo") private PushContext bar;
The message object will be encoded as JSON and be delivered as message argument of the onmessage JavaScript listener function
associated with the channel name. It can be a plain vanilla String, but it can also be a collection, map and even a javabean. For
supported argument types, see also Json#encode(Object).
By default the SSE channel is application scoped, i.e. any view/session throughout the web application having the same SSE channel open will
receive the same push message. The push message can be sent by all users and the application itself. This is useful for application-wide feedback triggered
by site itself such as real time updates of a certain page (e.g. site-wide statistics, top100 lists, stock updates, etc).
The optional scope attribute can be set to session to restrict the push messages to all views in the current user
session only. The push message can only be sent by the user itself and not by the application. This is useful for session-wide feedback triggered by user
itself (e.g. as result of asynchronous tasks triggered by user specific action).
<o:sse channel="someChannel" scope="session" ... />
The scope attribute can also be set to view to restrict the push messages to the current view only. The push message will not show
up in other views in the same session even if it's the same URL. The push message can only be sent by the user itself and not by the application. This is
useful for view-wide feedback triggered by user itself (e.g. progress bar tied to a user specific action on current view).
<o:sse channel="someChannel" scope="view" ... />
The scope attribute may not be an EL expression and allowed values are application, session and view,
case insensitive.
Additionally, the optional user attribute can be set to the unique identifier of the logged-in user, usually the login name or
the user ID. This way the push message can be targeted to a specific user and can also be sent by other users and the application itself. The value of the
user attribute must at least implement Serializable and have a low memory footprint, so putting entire user entity is not recommended.
E.g. when you're using container managed authentication or a related framework/library:
<o:sse channel="someChannel" user="#{request.remoteUser}" ... />
Or when you have a custom user entity around in EL as #{someLoggedInUser} which has an id property representing its identifier:
<o:sse channel="someChannel" user="#{someLoggedInUser.id}" ... />
When the user attribute is specified, then the scope defaults to session and cannot be set to
application. It can be set to view, but this is kind of unusual and should only be used if the logged-in user represented by
user has a shorter lifetime than the HTTP session (e.g. when your application allows changing a logged-in user during same HTTP session without
invaliding it — which is in turn poor security practice). If in such case a session scoped channel is reused, undefined behavior may occur when
user-targeted push message is sent. It may target previously logged-in user only. This can be solved by setting the scope to view, but better is
to fix the logout to invalidate the HTTP session altogether.
When the user attribute is an EL expression and it changes during an ajax request, then the SSE user will be actually switched, even though you
did not cover the <o:sse> component in any ajax render/update. So make sure the value is tied to at least a view scoped property in case
you intend to control it during the view scope.
In the server side, the push message can be targeted to the user specified in the user attribute via
PushContext#send(Object, Serializable). The push message can be sent by all users and the application itself. This is useful for
user-specific feedback triggered by other users (e.g. chat, admin messages, etc) or by application's background tasks (e.g. notifications, event listeners,
etc).
@Inject
@Push(type = SSE)
private PushContext someChannel;
public void sendMessage(Object message, User recipientUser) {
Long recipientUserId = recipientUser.getId();
someChannel.send(message, recipientUserId);
}
Multiple users can be targeted by passing a Collection holding user identifiers to PushContext#send(Object, Collection).
public void sendMessage(Object message, Group recipientGroup) {
Collection<Long> recipientUserIds = recipientGroup.getUserIds();
someChannel.send(message, recipientUserIds);
}
You can declare multiple push channels on different scopes with or without user target throughout the application. Be however aware that the same channel name can easily be reused across multiple views, even if it's view scoped. It's more efficient if you use as few different channel names as possible and tie the channel name to a specific push channel scope/user combination, not to a specific Faces view. In case you intend to have multiple view scoped channels for different purposes, best is to use only one view scoped channel and have a global JavaScript listener which can distinguish its task based on the delivered message. E.g. by sending the message in server as below:
Map<String, Object> message = new HashMap<>();
message.put("functionName", "someFunction");
message.put("functionData", functionData); // Can be Map or Bean.
someChannel.send(message);
Which is processed in the onmessage JavaScript listener function as below:
function someSseListener(message) {
window[message.functionName](message.functionData);
}
function someFunction(data) {
// ...
}
function otherFunction(data) {
// ...
}
// ...
The optional onopen JavaScript listener function can be used to listen on open of an SSE connection in client side. It will be
invoked with one argument:
channel: the channel name, useful in case you intend to have a global listener.<o:sse ... onopen="sseOpenListener" />
function sseOpenListener(channel) {
// ...
}
The optional onerror JavaScript listener function can be used to listen on a connection error whereby the browser will
automatically attempt to reconnect. This will be invoked when a transient connection error occurs (e.g. temporary network interruption) while the browser's
EventSource is still attempting to reconnect. This will not be invoked when the server has explicitly closed the connection (e.g.
unknown channel, or expired session or view), or when the EventSource API is not supported. Instead, the onclose will be invoked.
<o:sse ... onerror="sseErrorListener" />
function sseErrorListener(code, channel, event) {
if (code == 500) {
// Connection error. The browser will automatically attempt to reconnect.
}
}
The onerror JavaScript listener function will be invoked with three arguments:
code: synthetic HTTP-based close code as integer. Currently this is always 500 (connection error, browser will
auto-reconnect).channel: the channel name, useful in case you intend to have a global listener.event: the raw Event instance from the
EventSource API. Note that unlike WebSocket's CloseEvent, the SSE error event does not carry a close code or reason.
The optional onclose JavaScript listener function can be used to listen on the final close of an SSE connection. This will be
invoked when the EventSource API is not supported by the client, or when the server has explicitly closed the connection (e.g. on session or
view expiry, or unknown channel), or when the client has explicitly closed the connection via OmniFaces.Push.close(channel). This will
not be invoked when the browser can make an auto-reconnect attempt. Instead, the onerror will be invoked.
<o:sse ... onclose="sseCloseListener" />
function sseCloseListener(code, channel, event) {
if (code == -1) {
// EventSource API not supported by client.
} else if (code == 200) {
// Server explicitly closed the connection (e.g. expired session or view).
} else if (code == 204) {
// Client explicitly closed the connection via OmniFaces.Push.close().
} else if (code == 404) {
// Unknown channel (e.g. randomly guessed or spoofed by endusers or manually reconnected after session expiry).
} else {
// Abnormal close reason (as result of an error).
}
}
The onclose JavaScript listener function will be invoked with three arguments:
code: synthetic HTTP-based close code as integer. If this is -1, then the EventSource API is simply not
supported by the client. If this is 200, then the server explicitly closed the connection (e.g.
due to an expired session or view). If this is 204, then the client explicitly closed the connection via
OmniFaces.Push.close(channel). If this is 404, then the channel is unknown (e.g. randomly guessed or spoofed by endusers or
manually reconnected after the session is expired).channel: the channel name, useful in case you intend to have a global listener.event: the raw Event instance, if
available. This is present when the server closed the connection (codes 200 and 404), but absent when the EventSource
API is not supported (code -1) or the client explicitly closed the connection (code 204).
When an SSE connection has been opened, a new CDI SseEvent will be fired with @Opened
qualifier. When the user attribute of the <o:sse> changes, a new CDI SseEvent will be fired with
@Switched qualifier. When an SSE connection has been closed, a new CDI SseEvent will be fired with
@Closed qualifier. They can only be observed and collected in an application scoped CDI bean as below. Observing in
a request/view/session scoped CDI bean is not possible as there's no means of a HTTP request anywhere at that moment.
@ApplicationScoped
public class SseObserver {
public void onOpen(@Observes @Opened SseEvent event) {
String channel = event.getChannel(); // Returns <o:sse channel>.
Long userId = event.getUser(); // Returns <o:sse user>, if any.
// Do your thing with it. E.g. collecting them in a concurrent/synchronized collection.
// Do note that a single person can open multiple SSE connections on same channel/user.
}
public void onSwitch(@Observes @Switched SseEvent event) {
String channel = event.getChannel(); // Returns <o:sse channel>.
Long currentUserId = event.getUser(); // Returns current <o:sse user>, if any.
Long previousUserId = event.getPreviousUser(); // Returns previous <o:sse user>, if any.
// Do your thing with it. E.g. updating in a concurrent/synchronized collection.
}
public void onClose(@Observes @Closed SseEvent event) {
String channel = event.getChannel(); // Returns <o:sse channel>.
Long userId = event.getUser(); // Returns <o:sse user>, if any.
// Do your thing with it. E.g. removing them from collection.
}
}
You could take the opportunity to send another push message to an application scoped channel, e.g. "User X has been logged in" (or out) when a session scoped channel is opened (or closed).
If the SSE channel is declared in a page which is only restricted to logged-in users with a specific role, then you may want to add the URL of the SSE connection to the set of restricted URLs.
The SSE request URL is composed of the URI prefix /omnifaces.sse/, followed by channel name. So, in case of for example
container managed security which has already restricted an example page /user/foo.xhtml to logged-in users with the example role
USER on the example URL pattern /user/* in web.xml like below,
<security-constraint>
<web-resource-collection>
<web-resource-name>Restrict access to role USER.</web-resource-name>
<url-pattern>/user/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>USER</role-name>
</auth-constraint>
</security-constraint>
.. and the page /user/foo.xhtml in turn contains a <o:sse channel="foo">, then you need to add a restriction on SSE
connection request URL pattern of /omnifaces.sse/foo like below.
<security-constraint>
<web-resource-collection>
<web-resource-name>Restrict access to role USER.</web-resource-name>
<url-pattern>/user/*</url-pattern>
<url-pattern>/omnifaces.sse/foo</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>USER</role-name>
</auth-constraint>
</security-constraint>
As extra security, particularly for those public channels which can't be restricted by security constraints, the <o:sse> will register all
so far declared channels in the current HTTP session, and any incoming SSE connection request will be checked whether it matches a registered channel in the
current HTTP session. In case the channel is unknown (e.g. randomly guessed or spoofed by endusers or manually reconnected after the session is expired),
then the SSE connection will immediately be completed. Also, when the HTTP session gets destroyed, all session and view scoped channels which are still open
will explicitly be closed from server side. Only application scoped channels remain open and are still reachable from server end even when the session or
view associated with the page in client side is expired.
In case you'd like to trigger a push from business service side to an application scoped push channel, then you could make use of CDI events. First create a
custom bean class representing the push event something like PushEvent below taking whatever you'd like to pass as push message.
public final class PushEvent {
private final String message;
public PushEvent(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
Then use jakarta.enterprise.inject.spi.BeanManager#getEvent() to fire the CDI event.
@Inject
private BeanManager beanManager;
public void onSomeEntityChange(Entity entity) {
beanManager.getEvent().select().fire(new PushEvent(entity.getSomeProperty()));
}
Note that OmniFaces own Beans#fireEvent(Object, java.lang.annotation.Annotation...) utility method is insuitable as it is not allowed to use WAR
(front end) frameworks and libraries like Faces and OmniFaces in business service (back end) side.
Finally just @Observes it in some request or application scoped CDI managed bean in WAR and delegate to PushContext as
below.
@Inject
@Push(type = SSE)
private PushContext someChannel;
public void onPushEvent(@Observes PushEvent event) {
someChannel.send(event.getMessage());
}
Note that a request scoped bean wouldn't be the same one as from the originating page for the simple reason that there's no means of a HTTP request anywhere
at that moment. For exactly this reason a view and session scoped bean would not work (as they require respectively the Faces view state and HTTP session
which can only be identified by a HTTP request). A view and session scoped push channel would also not work, so the push channel really needs to be
application scoped. The FacesContext will also be unavailable in the above event listener method.
In case the trigger in business service side is an asynchronous service method which is in turn initiated in WAR side, then you could make use of callbacks
from WAR side. Let the business service method take a callback instance as argument, e.g. the java.util.function.Consumer functional interface.
@Asynchronous
public void someAsyncServiceMethod(Entity entity, Consumer<Object> callback) {
// ... (some long process)
callback.accept(entity.getSomeProperty());
}
And invoke the asynchronous service method in WAR as below.
@Inject
private SomeService someService;
@Inject
@Push(type = SSE)
private PushContext someChannel;
public void someAction() {
someService.someAsyncServiceMethod(entity, message -> someChannel.send(message));
}
This would be the only way in case you intend to asynchronously send a message to a view or session scoped push channel, and/or want to pass something from
FacesContext or the initial request/view/session scope along as (final) argument.
In case your web application is deployed to a server cluster with multiple nodes, and the push event could be triggered in a different node than where the client is connected to, then it won't reach the client. One solution is to activate and configure a JMS topic in the server configuration, trigger the push event via JMS instead of CDI, and use a JMS listener (a message driven bean, MDB) to delegate the push event to CDI.
Below is an example extending on the above given business service example.
@ApplicationScoped
public class PushManager {
@Resource(lookup = "java:/jms/topic/push")
private Topic jmsTopic;
@Inject
private JMSContext jmsContext;
public void fireEvent(PushEvent pushEvent) {
try {
Message jmsMessage = jmsContext.createMessage();
jmsMessage.setStringProperty("message", pushEvent.getMessage());
jmsContext.createProducer().send(jmsTopic, jmsMessage);
}
catch (Exception e) {
// Handle.
}
}
}
@MessageDriven(
activationConfig = {
@ActivationConfigProperty(propertyName = "destination", propertyValue = "java:/jms/topic/push")
}
)
public class PushListener implements MessageListener {
@Inject
private BeanManager beanManager;
@Override
public void onMessage(Message jmsMessage) {
try {
String message = jmsMessage.getStringProperty("message");
beanManager.fireEvent(new PushEvent(message));
}
catch (Exception e) {
// Handle.
}
}
}
Then, in your business service, instead of using BeanManager#fireEvent() to fire the CDI event,
@Inject
private BeanManager beanManager;
public void onSomeEntityChange(Entity entity) {
beanManager.fireEvent(new PushEvent(entity.getSomeProperty()));
}
use the newly created PushManager#fireEvent() to fire the JMS event from one server node of the cluster, which in turn will fire the CDI event
in all server nodes of the cluster.
@Inject
private PushManager pushManager;
public void onSomeEntityChange(Entity entity) {
pushManager.fireEvent(new PushEvent(entity.getSomeProperty()));
}
In case you'd like to perform complex UI updates, then easiest would be to put <f:ajax> inside <o:sse>. Here's an
example:
<h:panelGroup id="foo">
... (some complex UI here) ...
</h:panelGroup>
<h:form>
<o:sse channel="someChannel" scope="view">
<f:ajax event="someEvent" listener="#{bean.pushed}" render=":foo" />
</o:sse>
</h:form>
Here, the push message simply represents the ajax event name. You can use any custom event name.
someChannel.send("someEvent");
An alternative is to combine <o:sse> with <h:commandScript>. E.g.
<h:panelGroup id="foo">
... (some complex UI here) ...
</h:panelGroup>
<o:sse channel="someChannel" scope="view" onmessage="someCommandScript" />
<h:form>
<h:commandScript name="someCommandScript" action="#{bean.pushed}" render=":foo" />
</h:form>
If you pass a Map<String,V> or a JavaBean as push message object, then all entries/properties will transparently be available as request
parameters in the command script method #{bean.pushed}.
| Info | Value |
|---|---|
| Component Type | org.omnifaces.cdi.push.SseComponent |
| Handler Class | None |
| Renderer Type | None |
| Description | None |
| Name | Required | Type | Description |
|---|---|---|---|
binding | false | jakarta.el.ValueExpression
(must evaluate to jakarta.faces.component.UIComponent)
| The ValueExpression linking this component to a property in a backing bean. |
channel | true | jakarta.el.ValueExpression
(must evaluate to java.lang.String)
| The name of the push channel. It may not be an EL expression and it may only contain alphanumeric characters, hyphens, underscores and periods. All open connections on the same channel will receive the same push message from the server. |
id | false | jakarta.el.ValueExpression
(must evaluate to java.lang.String)
| The component identifier for this component. This value must be unique within the closest parent component that is a naming container. |
onclose | false | jakarta.el.ValueExpression
(must evaluate to java.lang.String)
| The JavaScript event handler function that is invoked when the push connection is closed. |
onerror | false | jakarta.el.ValueExpression
(must evaluate to java.lang.String)
| The JavaScript event handler function that is invoked when a connection error has occurred. |
onmessage | true | jakarta.el.ValueExpression
(must evaluate to java.lang.String)
| The JavaScript event handler function that is invoked when a push message is received from the server. The function will be invoked with three
arguments: the push message, the channel name and the raw MessageEvent itself. |
onopen | false | jakarta.el.ValueExpression
(must evaluate to java.lang.String)
| The JavaScript event handler function that is invoked when the push connection is opened. The function will be invoked with one argument: the channel name. |
rendered | false | jakarta.el.ValueExpression
(must evaluate to boolean)
| Flag indicating whether or not this component should be rendered (during Render Response Phase), or processed on any subsequent form submit. The default value for this property is true. |
scope | false | jakarta.el.ValueExpression
(must evaluate to java.lang.String)
| The scope of the push channel. It may not be an EL expression and allowed values are application, session and
view, case insensitive. When the value is application, then all channels with the same name throughout the application will
receive the same push message. When the value is session, then only the channels with the same name in the current user session will receive
the same push message. When the value is view, then only the channel in the current view will receive the push message. The default scope is
application. When the user attribute is specified, then the default scope is session. |
user | false | jakarta.el.ValueExpression
(must evaluate to java.io.Serializable)
| The user identifier of the push channel, so that user-targeted push messages can be sent. All open connections on the same channel and user will
receive the same push message from the server. It must implement Serializable and preferably have low memory footprint. Suggestion: use
#{request.remoteUser} or #{someLoggedInUser.id}. |
Output generated by Vdldoc View Declaration Language Documentation Generator.