tags:

views:

1429

answers:

3

Hello, I'm trying to create a simulation for our web Portal and need to add custom HTTP headers. I am to assume the user has already been authenticated and these headers are just for storing user information (ie, "test-header: role=user; oem=blahblah; id=123;").

I've setup a filter to extract the header information but I can't find a way to inject the header information. They don't want it to be stored in cookies and maybe they will want to setup a global filter to include the headers on every page; is it possible to do something like this with the filter interface or through any other methods?

A: 

You can use addHeader.

kgiannakakis
A: 

You would need to utilize HttpServletRequestWrapper and provide your custom headers in when the various getHeader* methods are called.

laz
This won't actually add the headers to the request, will it? It's just providing them in the getHeaders() call. Is there not a way to add headers like firefox's Modify Headers add-on does? When using modify headers I could use PHP or java to print all the headers and it'd show the custom headers, but overloading the getHeader() method is just attaching the header before the servlet gets it. I don't see how java could add request headers, but I'm wondering how applications like Oracle Access Manager's do it.
ravun
A: 

Maybe you can store that information in the session:


import java.io.IOException;

import javax.servlet.Filter;
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;
import javax.servlet.http.HttpServletResponse;

/**
 * @author rodrigoap
 * 
 */
public class UserInfoFilter implements Filter {

    /**
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {
     // TODO
    }

    /**
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
     *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain filterChain) throws IOException, ServletException {
     if (!(request instanceof HttpServletRequest))
      throw new ServletException("Can only process HttpServletRequest");
     if (!(response instanceof HttpServletResponse))
      throw new ServletException("Can only process HttpServletResponse");
     HttpServletRequest httpRequest = (HttpServletRequest) request;
     HttpServletResponse httpResponse = (HttpServletResponse) response;

     httpRequest.getSession().setAttribute("role", "user");
     httpRequest.getSession().setAttribute("id", "123");
                filterChain.doFilter(request, response);
    }

    /**
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig filterConfig) throws ServletException {
     // TODO
    }

}
rodrigoap