November 2, 2005 - 07:53 UTC - Tags: Web services Axis cookie
You may sometimes need to set or retrieve cookies on axis connections to transfer authentication tokens or similar.
Setting a cookie on an axis client requestTo set a cookie on an axis client, you can add a handler. Below is source code for a handler, that fetches the currently incoming HttpServletRequest (say to a web site), extracts a cookie and puts the cookie on the axis request (to the web service).
public class CookieHandler extends BasicHandler {
public void invoke(MessageContext context) throws AxisFault {
HttpServletRequest request = someMethodReturningCurrentRequest();
Cookie cookies[] = request.getCookies();
Cookie cookie = null;
for (int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
if (name.equals("cookiename")) {
cookie = cookies[i];
}
}
if (cookie != null) {
context.setProperty(HTTPConstants.HEADER_COOKIE,
cookie.getName() + "=" + cookie.getValue());
}
}
}
To make the axis client use this cookie, we have to add it (or create) a client-config.wsdd. This file should reside in the classes directory in you war-archive.
client-config.wsdd:
<?xml version="1.0" encoding="UTF-8"?>
<deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
<globalConfiguration>
<requestFlow>
<handler type="java:com.abb.commons.contentcockpit.servlet.CookieHandler"/>
</requestFlow>
</globalConfiguration>
<transport name="http" pivot="java:org.apache.axis.transport.http.HTTPSender"/>
</deployment>
To make axis actually use cookies, MaintainSession has to be set to true (I discovered this reading the source code of HttpHandler - search for "don't forget the cookies....mmm..cookies" :-) ):
((MyServiceStub) myService).setMaintainSession(true);
Retrieving a cookie on a web service callThe following code retrieves a cookie from an incoming call to web service (SOAP/HTTP):
MessageContext context = MessageContext.getCurrentContext();
if (context != null) {
HttpServletRequest req = (HttpServletRequest) context
.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
if (req != null) {
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("cookiename")) {
//do something with cookie
}
}
}
}
}