Search code examples
javaweb-servicesjax-wsservlet-filtersthread-local

What is the best way to set ThreadLocal with Id from request messageHeader on Server side JAX-WS Webservice


I have a JAX-WS Webservice exposed to client. When Client invokes it, messageheader will be populated with UserId. I am trying to set this value in thread local using utility class when request comes from client and remove it before sending response back to client so It can be accessible from anywhere using that variable for that thread scope. What is the best way to implement this.Can I use Filters on server Side or I have to go with Jax-Ws Handlers to initialize this value.And also Can we remove this value before sending response with Jax-ws handlers.

is there any other way to implement it?


Solution

  • Assuming by messageheader you mean SOAP <Header> (and not HTTP header):

    If you use a Servlet Filter, to retrieve and set a threadlocal you'll have to parse the SOAP XML yourself to access the UserId value.

    If you use a JAX-WS handler, the SOAP is already parsed for you into an object model. If you just need to pass the UserId value to the web service part of the application, in your handler you can simply set the value on the SOAPMessageContext as is the example here. You can also set a thread local as you specified. To remove or clear the threadlocal you could either use a servlet filter or simply check the MESSAGE_OUTBOUND_PROPERTY on the SOAPMessageContext in your handler: if it's inbound, your handler is being invoked on the web service request, so you want to read the message header and set the threadlocal value. If it's outbound, your handler is being asked to handle the web service response, so you'll want to remove.