Java EE 7 WebSocket example

1. Createa a Java EE Web application called MyWebSocket for example.
2. In index.html:

<!DOCTYPE html>
        <title>Start Page</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script language="javascript">
            var ws;
            function connect() {
                ws = new WebSocket("ws://localhost:8080/MyWebSocket/sockOne");
                ws.onmessage = onMessage;
            function onMessage(evt) {
                var dataarr =;
                document.getElementById("valueElement").innerHTML = dataarr;
            window.addEventListener("load", connect, false);
        <h1>Hello World!</h1>
        <b>Value: </b>
        <b id="valueElement">no data yet</b>

2. Create a class Called WebSocketEndpoint. Here the most important annotations are @ServerEndpoint, @OnOpen, @OnClose and @OnError, in these methods you put whatever you want to get executed when these events happen:

package com.vvirlan.websocket;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

 * @author vvirlan
public class WebSocketEndpoint {

    private static final Logger LOGGER = Logger.getLogger("WebSocketEndpoint");
    private static Queue<Session> sessionQueue = new ConcurrentLinkedQueue<>();

    public static void send(double number) {
        String toSend = String.format("%f", number);
        try {
            for (Session session : sessionQueue) {
                LOGGER.log(Level.INFO, "Sent: {0}", toSend);
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.toString());

    public void openConnection(Session session) {
        LOGGER.log(Level.INFO, "Connection opened");

    public void closeConnection(Session session) {
        LOGGER.log(Level.INFO, "Connection closed");

    public void error(Session session, Throwable th) {
        LOGGER.log(Level.WARNING, "Connection errorred");
        LOGGER.log(Level.WARNING, th.toString());


3. The bean which will produce our fake data. It gets injected a TimerService as a @Resource and when @Timeout happens it invokes the send method of our endpoint:

package com.vvirlan.websocket;

import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

 * @author vvirlan
 * Generates a double every second and calls the endpoint for updating the clients
public class GeneratorBean {
    @Resource TimerService timerService;
    private Random random;
    private volatile double number = 777.0;
    private static final Logger logger = Logger.getLogger("GeneratorBean");
    public void init() {
        logger.log(Level.INFO, "Initializing EJB");
        random = new Random();
        timerService.createIntervalTimer(1000, 1000, new TimerConfig());
    public void timeout() {
        number = 1.5 * (random.nextInt(100));

JSF simple ajax example

Here is a simple AJAX example in JSF (run on Glassfish).
Just to note: for sending the value to the bean you use the execute attribute of f:ajax, and for displaying the output from the beans’s getter, you use the render attribute.

1. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">






2. The xhtml page:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns=""
        <title>Facelet Title</title>
        Hello from Facelets
            <h:inputText id="msg" value="#{myBean.text}"/>
        <h:commandButton id="submit" value="Submit">
            <f:ajax event="click"  execute="msg" render="outText"/>
            <h:outputText value="The message: #{myBean.text}" id="outText">

3. The Bean:

package com.mycompany.ajaxtest;

import javax.enterprise.inject.Model;

 * @author vvirlan
public class MyBean implements Serializable {
    private String text = "defaullt";
    public void message() {
        System.out.println("The message "+text);

    public String getText() {
        System.out.println("getText message "+text);
        return text;

    public void setText(String text) {
        System.out.println("setText message "+text);
        this.text = text;

[java] check password against DB

To check the password against the database encoded value is simple, but it is not supported out of the box. You’ll have to convert the generated hash into hex format

		byte[] encoded = md.digest();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < encoded.length; i++) {
			sb.append(Integer.toString((encoded[i] & 0xff) + 0x100, 16).substring(1));

Here’s a complete example:

public boolean validate(String username, String password) {
		final Query query = em.createQuery("SELECT u FROM User u WHERE u.username = :username");
		query.setParameter("username", username);

		List<User> foundUsers = (List<User>) query.getResultList();
		if (foundUsers == null || foundUsers.isEmpty()) {
			return false;
		User foundUser = foundUsers.get(0);
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("SHA");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
		byte[] encoded = md.digest();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < encoded.length; i++) {
			sb.append(Integer.toString((encoded[i] & 0xff) + 0x100, 16).substring(1));

		if (sb.toString().equals(foundUser.getPassword())) {
			return true;

		return false;

web.xml examples for all versions of Servlet

1. Servlet 3.1

<web-app xmlns=""

2. Servlet 3.0

<web-app xmlns=""

3. Servlet 2.5

<web-app xmlns=""

4. Servlet 2.4

<web-app xmlns=""

  <display-name>Servlet 2.4 Web Application</display-name>

5. Servlet 2.3

 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "" >

  <display-name>Servlet 2.3 Web Application</display-name>

[Starter] EJB Session Bean based Web Server and Servlet client

EJB Session Bean based Web Server and Servlet client in Netbeans

1. Create a Class Library project which will hold your Remote EJB interfaces


2. Create new interface called WsHello

package com.vvirlan.ejb;
import javax.ejb.Remote;
public interface WsHello {
    public String sayHello(String name);

3. Create a new Project of type EJB Module
4. Create a new class in the EJB Module this class will implement your interface defined in the Class Library you defined earlier

package com.vvirlan.ejb;

import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;
public class WsHelloImpl implements WsHello {
    private String msg = "Hello! ";
    public String sayHello(String name) {
        return msg + name;

5. Create a Web Application and a new Servlet in it. Here you add the annotation @EJB to autowire your interface.

package com.vvirlan.servlet;

import com.vvirlan.ejb.HelloServiceBean;
import com.vvirlan.ejb.WsHello;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WsServlet extends HttpServlet {

    private WsHello hello;
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String result = hello.sayHello("Vlad");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<title>Servlet WsServlet</title>");            
            out.println("<h1>Servlet WsServlet at " + request.getContextPath() + "</h1>");
            out.println("<h1>Servlet WsServlet at " + result + "</h1>");

6. Add the Class Library as a dependency in your web application project. Now all errors should solve by themselves.


JSF – Add OmniFaces to your project

1. In pom.xml


2. You should put your xhtml pages under:


3. In your bean for example. Here strange is a xhtml file under the folder stated in point 2:

 ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
 ec.redirect(ec.getRequestContextPath() + "strange");