I need to create a Filter and modify header values set in request Object. How we can modify headers in request Object using Filter?, there is no setHeader method available in request Object.
Asked
Active
Viewed 1.7k times
2
-
Are you talking about HTTP? – Mar 08 '13 at 13:15
-
yes HttpServletRequest request Object – Prateek Shrivastava Mar 08 '13 at 13:16
-
Use `HttpServletRequestWrapper` for this purposes. – bsiamionau Mar 08 '13 at 13:18
-
Does this answer your question? [Adding an HTTP Header to the request in a servlet filter](https://stackoverflow.com/questions/2811769/adding-an-http-header-to-the-request-in-a-servlet-filter) – damndemon Aug 11 '22 at 15:07
2 Answers
5
You can use javax.servlet.http.HttpServletRequestWrapper
to wrap the HttpServletRequest
object passed by the server.
In the wrapper class you need to override getHeader
method and return modified value of header.
You can refer to similar post over here Modify request parameter with servlet filter

Community
- 1
- 1

Rutesh Makhijani
- 17,065
- 2
- 26
- 22
-1
You can import Collectors using
import java.util.stream.Collectors;
Add the method below into your class.
private Map<String, String> convertHeadersToLowerCase(Map<String, String> headers) {
return headers
.entrySet()
.stream()
.collect(Collectors.toMap(entry -> entry.getKey().toLowerCase(), entry -> entry.getValue()));
}
Then before returning headers in the response, you should ensure they are converted before returning by adding the following into the Controller of your Response method:
requestHeaders = convertRequestHeadersToLowerCase(requestHeaders);

Shanteshwar Inde
- 1,438
- 4
- 17
- 27

Josh
- 1
- 2
-
OP asked about modifying headers in the *request*, not the *response*. – Max Leske Feb 12 '21 at 10:47