How to use a servlet filter in Java to change an incoming servlet request url?
- Implement
javax.servlet.Filter
. - In
doFilter()
method, cast the incomingServletRequest
toHttpServletRequest
. - Use
HttpServletRequest#getRequestURI()
to grab the path. - Use straightforward
java.lang.String
methods likesubstring()
,split()
,concat()
and so on to extract the part of interest and compose the new path. - Use either
ServletRequest#getRequestDispatcher()
and thenRequestDispatcher#forward()
to forward the request/response to the new URL (server-side redirect, not reflected in browser address bar), or cast the incomingServletResponse
toHttpServletResponse
and thenHttpServletResponse#sendRedirect()
to redirect the response to the new URL (client side redirect, reflected in browser address bar). - Register the filter in
web.xml
on anurl-pattern
of/*
or/Check_License/*
, depending on the context path, or if you're on Servlet 3.0 already, use the@WebFilter
annotation for that instead.
Don't forget to add a check in the code if the URL needs to be changed and if not, then just call FilterChain#doFilter()
, else it will call itself in an infinite loop.
Alternatively you can also just use an existing 3rd party API to do all the work for you, such as Tuckey's UrlRewriteFilter which can be configured the way as you would do with Apache's mod_rewrite
.
Filter & RequestDispatcher to change URL effect on existing filters
What I ended up doing was to place this new filter last in the web.xml definiton.
This rewrite filter needed to be last on the chain, since using the request dispatcher
forward
method would not break functionallity or inhibit the running of the other filters.
How to change servlet request body in java filter?
XSSFilter.java
public class XSSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
XSSRequestWrapper wrappedRequest = new XSSRequestWrapper(
(HttpServletRequest) request);
String body = IOUtils.toString(wrappedRequest.getReader());
if(!"".equals(body))
{
JSONObject oldJsonObject = new JSONObject(body);
JSONObject newJsonObject = new JSONObject();
for(String key : oldJsonObject.keySet())
{
newJsonObject.put(key, XSSUtils.stripXSS(oldJsonObject.get(key).toString()));
}
wrappedRequest.resetInputStream(newJsonObject.toString().getBytes());
}
chain.doFilter(wrappedRequest, response);
}
}
XSSRequestWrapper .java
public class XSSRequestWrapper extends HttpServletRequestWrapper {
private byte[] rawData;
private HttpServletRequest request;
private ResettableServletInputStream servletStream;
public XSSRequestWrapper(HttpServletRequest request) {
super(request);
this.request = request;
this.servletStream = new ResettableServletInputStream();
}
public void resetInputStream(byte[] newRawData) {
servletStream.stream = new ByteArrayInputStream(newRawData);
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (rawData == null) {
rawData = IOUtils.toByteArray(this.request.getReader());
servletStream.stream = new ByteArrayInputStream(rawData);
}
return servletStream;
}
@Override
public BufferedReader getReader() throws IOException {
if (rawData == null) {
rawData = IOUtils.toByteArray(this.request.getReader());
servletStream.stream = new ByteArrayInputStream(rawData);
}
return new BufferedReader(new InputStreamReader(servletStream));
}
private class ResettableServletInputStream extends ServletInputStream {
private InputStream stream;
@Override
public int read() throws IOException {
return stream.read();
}
}
}
XSSUtils .java
public class XSSUtils {
private XSSUtils()
{
}
public static String stripXSS(String value) {
return value == null ? value : escapeHtml4(value);
}
}
How to attach a filter to a servlet or URL pattern
Add this annotation to the Filter class. It maps all the requests to this filter.
If you are interested in only specific requests url's you should map only those url patterns.
@WebFilter("/*")
public class ExampleFilter implements Filter {
// your filter..
}
Related Topics
What's the Difference Between Instant and Localdatetime
How to Build Jars from Intellij Properly
How to Lock a File Using Java (If Possible)
How to Put a Control in the Jtableheader of a Jtable
How to Set the Environment Variables For Java in Windows
How to Compare Objects by Multiple Fields
Want Current Date and Time in "Dd/Mm/Yyyy Hh:Mm:Ss.Ss" Format
Difference Between Wait() and Sleep()
Java: Convert List≪String≫ to a Join()D String
Netbeans Gui Editor Generating Its Own Incomprehensible Code
How Many Threads Can a Java Vm Support
Servlet For Serving Static Content
Number of Lines in a File in Java
Unicode Equivalents For \W and \B in Java Regular Expressions