A Single Line of Code Which Keeps Your REST/Hessian/HTTP Client State

Stateful HTTP-services require you to pass the jsessionid back and forth between a Java-based HTTP client (like Hessian, REST-client like Jersey/RESTeasy, SOAP, or plain HTTP-connection) as URL-extension or cookie. JDK 1.6 comes with java.net.CookieManager which handles all the bookkeeping for you. I modified the already introduced Hessian example to be stateful - it takes a single (but bold) line of code:

import java.net.CookiePolicy;
import java.net.CookieManager;
import java.net.CookieHandler;
public class HessianStatefulTimeEndpoint {
    private TimeService timeService;

    public void initProxy() throws MalformedURLException {
        CookieHandler.setDefault(new CookieManager(null /*=default in-memory store*/, CookiePolicy.ACCEPT_ALL));
        String url = "http://localhost:8080/EJB31AndHessian/TimeService";
        HessianProxyFactory factory = new HessianProxyFactory();
        this.timeService = (TimeService) factory.create(TimeService.class,url);

    public void statefulness(){
        int numberOfSessions = this.timeService.getNumberOfSessions();
        int nextInvocation = this.timeService.getNumberOfSessions();
On the server server you can inject @SessionScoped beans into the HessianServlet:
public class HessianTimeEndpoint extends HessianServlet implements TimeService{

    CurrentTime currentTime;

public class CurrentTime implements Serializable{
    private static AtomicInteger instanceCount = new AtomicInteger(0);
    public void onNewSession(){
        System.out.println("On new session: " + new Date());
    public int getNumberOfSessions(){
        return instanceCount.get();
    public long nanos(){
        return System.nanoTime();

You will find the executable project (tested with Netbeans 7 and Glassfish v3.1) in: http://kenai.com/projects/javaee-patterns/ [project name: EJB3AndHessian - the original project was updated].

[See also Service Facade pattern, page 69 Real World Java EE Patterns - Rethinking Best Practices]


This is really smart Adam!
Thx for the hint!

Posted by Joachim Arrasz on May 11, 2011 at 01:07 PM CEST #

Interesting tips, you have covered the topic well and thanks for sharing information.

Posted by JP@ Java classpath tutorial on May 22, 2011 at 10:19 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments