One of the most attractive features is JSF 2.3 added native web socket support, it means you can write real-time applications with JSF and no need extra effort.
To enable web socket support, you have to add javax.faces.ENABLE_WEBSOCKET_ENDPOINT in web.xml.
The first button sends a fixed hello string, and the second button accepts user custom message.
sendMessage and sendMessage2 will call sendPushMessage which utilizes the injected pushContext to send messages to the defined channel.
In the facelets template, onmessage indicates which handlers(onMessage method) will be used when messages is coming from the specified channel(helloChannel).
onMessage method will add the message body from web socket channel and put it into the content of message block.
Try click first button or input some messages and click the second button, the response message from server side will be displayed.
Scope
f:websocket has an attribute scope which accepts application, session, or view as its value, it is not difficult to understand.
Another attribute user can be used for identifying different client users, it can be a user id or serializable object that stands for a user. It is useful to communicate with a specific user.
Create a backing bean.
@ViewScoped@Named("scopeBean")publicclassScopeBeanimplementsSerializable {privatestaticfinalLogger LOG =Logger.getLogger(ScopeBean.class.getName()); @Inject @PushPushContext applicationChannel; @Inject @PushPushContext sessionChannel; @Inject @PushPushContext viewChannel; @Inject @PushPushContext userChannel;publicvoidpushToApplicationChannel() {applicationChannel.send("sent to applicationChannel at ::"+LocalDateTime.now()); }publicvoidpushToSessionChannel() {sessionChannel.send("sent to sessionChannel at ::"+LocalDateTime.now()); }publicvoidpushToViewChannel() {viewChannel.send("sent to viewChannel at ::"+LocalDateTime.now()); }publicvoidpushToUserChannel() {userChannel.send("sent to userChannel at ::"+LocalDateTime.now(),"user"); }publicvoidpushToMultiUsersChannel() {userChannel.send("sent to userChannel at ::"+LocalDateTime.now(),Arrays.asList("user","hantsy")); }}
To demonstrate different cases, we defined a series of PushContext in the backing bean.
JSF 2.3 provides a WebsocketEvent, in the backend codes, you can observe it when it is opened (via CDI @Opened qualifier) or closed(via CDI @Closed qualifier).
Besides onmessage attribute of f:websocket, it also provides other two attributes onopen and onclose to listen the web socket connection when it is opened or closed. connected allow you set it disconnected by default, and use JSF built-in jsf.push.open() to connect to server side manually.
Create a simple backing bean.
@ViewScoped@Named("eventBean")publicclassEventBeanimplementsSerializable {privatestaticfinalLogger LOG =Logger.getLogger(EventBean.class.getName()); @Inject @PushPushContext eventChannel;publicvoidsendMessage() {eventChannel.send("event message was sent at::"+LocalDateTime.now()); }}
The facelets template file:
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsf="http://xmlns.jcp.org/jsf"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
>
<h:head>
<title>JSF 2.3: Websocket Sample</title>
<script>
function onMessage(message, channel, event) {
console.log('Client onMessage listener: message: ' + message + ', channel:' + channel + ", event:" + event);
document.getElementById("message").innerHTML = message;
}
function onOpen(channel) {
console.log('Client onOpen listener: channel:' + channel);
}
function onClose(code, channel, event) {
console.log('Client onClose listener: code: ' + code + ', channel:' + channel + ", event:" + event);
if (code === -1) {
// Web sockets not supported by client.
} else if (code === 1000) {
// Normal close (as result of expired session or view).
} else {
// Abnormal close reason (as result of an error).
}
}
</script>
</h:head>
<h:body>
<h1>JSF 2.3: Websocket Events </h1>
<div id="message" />
<hr />
<h:form id="form">
<div>
<h:commandButton onclick="jsf.push.open('eventChannel')" value="Open Event Channel">
<f:ajax />
</h:commandButton>
<h:commandButton onclick="jsf.push.close('eventChannel')" value="Close Event Channel">
<f:ajax />
</h:commandButton>
</div>
<h:commandButton
id="sendMessage"
type="submit"
action="#{eventBean.sendMessage}" value="Send Message">
<f:ajax />
</h:commandButton>
</h:form>
<f:websocket id="eventChannel"
channel="eventChannel"
onopen="onOpen"
onclose="onClose"
onmessage="onMessage"
connected="false"/>
</h:body>
</html>
In the backend codes, use pushContext send the f:ajax event name as content.
Another alternative here, use h:commandScript(newly added in JSF 2.3) with f:websocket instead, setonmessage handler as the name attribute of h:commandScript.
In JSF internally, JSF expose a default endpoint(/javax.faces.push/channelName) to serve the web socket connections. You can protect it as other web resources.
<security-constraint>
<web-resource-collection>
<web-resource-name>Restrict access to role USER.</web-resource-name>
<url-pattern>/user/*</url-pattern>
<url-pattern>/javax.faces.push/foo</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>USER</role-name>
</auth-constraint>
</security-constraint>
Source codes
Grab the source codes from my GitHub account, and have a try.