Modify request parameter with servlet filter
As you've noted HttpServletRequest
does not have a setParameter method. This is deliberate, since the class represents the request as it came from the client, and modifying the parameter would not represent that.
One solution is to use the HttpServletRequestWrapper
class, which allows you to wrap one request with another. You can subclass that, and override the getParameter
method to return your sanitized value. You can then pass that wrapped request to chain.doFilter
instead of the original request.
It's a bit ugly, but that's what the servlet API says you should do. If you try to pass anything else to doFilter
, some servlet containers will complain that you have violated the spec, and will refuse to handle it.
A more elegant solution is more work - modify the original servlet/JSP that processes the parameter, so that it expects a request attribute instead of a parameter. The filter examines the parameter, sanitizes it, and sets the attribute (using request.setAttribute
) with the sanitized value. No subclassing, no spoofing, but does require you to modify other parts of your application.
Modifying HttpServletRequest parameters with a Servlet Filter doesn't seem to work
Your remove method modifies the mutable map returned by getParameterMap()
. But the next call to getParameterMap()
reconstructs a new mutable map containing all the parameters of the wrapped query.
The mutable map should be constructed when the FilteredRequest
is constructed, and it should be stored in an instance field.
Related Topics
How to Restart a Java Application
Difference Between Java Hh:Mm and Hh:Mm on Simpledateformat
Explicit Casting from Super Class to Subclass
Why Does String.Split Need Pipe Delimiter to Be Escaped
Do Spurious Wakeups in Java Actually Happen
How to Re-Run Failed Junit Tests Immediately
Runnable Jars Missing Images/Files (Resources)
Mapping Postgresql JSON Column to a Hibernate Entity Property
Interview Question: Check If One String Is a Rotation of Other String
How to Get Frequency from Fft Result
How to Get Vm Arguments from Inside of Java Application
Cannot Parse String in Iso 8601 Format, Lacking Colon in Offset, to Java 8 Date
How Good Is Java's Uuid.Randomuuid
Javafx "Location Is Required." Even Though It Is in the Same Package
Initial Size for the Arraylist
How to Tackle Daylight Savings Using Timezone in Java
Java: Error: Variable Might Not Have Been Initialized
Understanding the Workings of Equals and Hashcode in a Hashmap