I am trying to write a filter that can retrieve the request URL, but I'm not sure how to do so.
Here is what I have so far:
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class MyFilter implements Filter {
public void init(FilterConfig config) throws ServletException { }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
chain.doFilter(request, response);
String url = ((HttpServletRequest) request).getPathTranslated();
System.out.println("Url: " + url);
}
public void destroy() { }
}
When I hit a page on my server, the only output I see is "Url: null".
What is the correct way to get the requested URL from a given ServletRequest object in a Filter?
Is this what you're looking for?
if (request instanceof HttpServletRequest) {
String url = ((HttpServletRequest)request).getRequestURL().toString();
String queryString = ((HttpServletRequest)request).getQueryString();
}
To Reconstruct:
System.out.println(url + "?" + queryString);
Info on HttpServletRequest.getRequestURL()
and HttpServletRequest.getQueryString()
.