views:

6

answers:

1

I need to retrieve some information sent in the HTTP headers from within a Web Service. How can I achieve this?

A: 

It depends on the language and web service framework you want to use.

Your question title mentions "Servlet Filter" so I assume you work with a Java application container. If your ws framework does not support the of mapping request headers into value objects, you could use a Servlet Filter that processes the header and stores the information somewhere you can retrieve it later. The best option would be to put it in a request attribute. If you can't get to the HttpServletRequest later (which probably makes you ask this question), you can store it into a ThreadLocal variable, but this is trickier.

I'll give you a minimal example:

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class Filter implements javax.servlet.Filter {
  public ThreadLocal<String> local;

  @Override
  public void doFilter(ServletRequest req, ServletResponse response, 
    FilterChain chain) throws ServletException, IOException {

    HttpServletRequest request = (HttpServletRequest)req;
    String bar = request.getHeader("foo");
    local.set(bar);
    // you can now retrieve the header value in your code with Filter.local.get()
    try {
      chain.doFilter(request, response);
    } finally {
      local.remove(); // clean up
    }
  }

  @Override
  public void destroy() {
  }

  @Override
  public void init(FilterConfig arg0) throws ServletException {
    local = new ThreadLocal<String>();
  }
}

It works, but in a real life implementation you should store an Object of your own Class in the ThreadLocal (e.g. a Bean) instead of a mere String. You should consider putting the ThreadLocal variable outside your Filter (e.g. as a static variable somewhere in a more logical place).

ivy
I actually solved this by using the @WebServiceContext annotation since I am using JAX-WS
GLL