/java/

JEE Stateless, Statefull and SessionScoped simple example

2014-06-19 14:05:51

GitHub: https://github.com/szalek/jee-stateless-statefull-sessionscoped

package pl.btbw;

import javax.ejb.EJB;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("state")
package pl.btbw;

import javax.ejb.EJB;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("state")
public class SlSfResource {

    @EJB
    private CounterLess less;

    @EJB
    private CounterFull full;

    @Inject
    private CounterSessionScoped sessionScoped;

    @GET
    @Path("/less")
    public String testLess() {
        less.increase();
        less.increase();
        return "test-less: " + less.getNumber();
    }

    @GET
    @Path("/full")
    public String testFull() {
        full.increase();
        full.increase();
        return "test-full:" + full.getNumber();
    }

    @GET
    @Path("/session")
    public String testSession() {
        sessionScoped.increase();
        sessionScoped.increase();
        return "test-sessionScoped:" + sessionScoped.getNumber();
    }

}

CounterFull.java

package pl.btbw;

import javax.ejb.Stateful;

@Stateful
public class CounterFull {

    private int number = 1;

    public void increase() {
        number++;
    }

    public int getNumber() {
        return number;
    }
}

CounterLess.java

package pl.btbw;

import javax.ejb.Stateless;

@Stateless
public class CounterLess {

    private int number = 1;

    public void increase() {
        number++;
    }

    public int getNumber() {
        return number;
    }
}

CounterSessionScoped.java

package pl.btbw;

import javax.enterprise.context.SessionScoped;
import java.io.Serializable;

@SessionScoped
public class CounterSessionScoped implements Serializable {

    private int number = 1;

    public void increase() {
        number++;
    }

    public int getNumber() {
        return number;
    }
}