Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an HTTP Header to the request in a servlet filter

I'm integrating with an existing servlet that pulls some properties out of the HTTP header. Basically, I'm implementing an interface that doesn't have access to the actual request, it just has access to a map of k->v for the HTTP headers.

I need to pass in a request parameter. The plan is to use a servlet filter to go from parameter to header value but of course the HttpServletRequest object doesn't have an addHeader() method.

Any ideas?

like image 200
Mason Avatar asked May 11 '10 14:05

Mason


People also ask

How do I add HTTP header to request?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.

Which methods are used by a servlet to set headers of an HTTP response?

void setContentLength(int len) Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.

What is a HTTP request header?

A request header is an HTTP header that can be used in an HTTP request to provide information about the request context, so that the server can tailor the response. For example, the Accept-* headers indicate the allowed and preferred formats of the response.


1 Answers

Extend HttpServletRequestWrapper, override the header getters to return the parameters as well:

public class AddParamsToHeader extends HttpServletRequestWrapper {     public AddParamsToHeader(HttpServletRequest request) {         super(request);     }      public String getHeader(String name) {         String header = super.getHeader(name);         return (header != null) ? header : super.getParameter(name); // Note: you can't use getParameterValues() here.     }      public Enumeration getHeaderNames() {         List<String> names = Collections.list(super.getHeaderNames());         names.addAll(Collections.list(super.getParameterNames()));         return Collections.enumeration(names);     } } 

..and wrap the original request with it:

chain.doFilter(new AddParamsToHeader((HttpServletRequest) request), response); 

That said, I personally find this a bad idea. Rather give it direct access to the parameters or pass the parameters to it.

like image 192
BalusC Avatar answered Sep 21 '22 10:09

BalusC