Maintaining state in Java Webservice(JAX-WS)

Maintaining state in Java Webservice(JAX-WS)


Introduction

This little article start point is the need of get the current session from a flash swf.
I try to explain: The web application has a login form and after the user is authenticated a session is created and mantained, so the need is to access to this value into the session from flash that calls a webservice in the same service.

recapitulate.

Server side: JSP, Servlet etc. for user login.
Server side: Webservice for reporting stuff.

Client side: html form for login
Client side: flash swf (created with flex) for reporting gui. it access the webservice to obtaining reporting data and draw it. when the webservice is called the session data created in login step is required.


The Webservice

The webservice is created like in the previouse article.
But in order to get the current session a MessageContext is required.
So declare it by the @Resouce annotation, and get the HttpSession from it!

@WebService()
public class testWS {

    @Resource
    private WebServiceContext context;
    /**
     * Web service operation
     */
    @WebMethod(operationName = "sayHello")
    public String sayHello(@WebParam(name = "name")
    String name)
    {
        String ret = "";
        MessageContext mc = context.getMessageContext();
        HttpSession session = ((HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST)).getSession(false);
        if (session == null)
        {ret =  "hello: NO SESSION";}
        else
        {
            Enumeration en = session.getAttributeNames();
            while (en.hasMoreElements())
            {
                String key = (String) en.nextElement();
                ret += key + " " + session.getAttribute(key) + "\r\n";
            }
        }
        return ret;

    }

}

That's all.
The client side you can see in the previous article


Conclusion

For a complete discussion about session mantaining

No comments: