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?
A filter is an object that can transform the header and content (or both) of a request or response. Filters differ from web components in that filters usually do not themselves create a response.
Class HttpServletRequestWrapper. Provides a convenient implementation of the HttpServletRequest interface that can be subclassed by developers wishing to adapt the request to a Servlet. This class implements the Wrapper or Decorator pattern. Methods default to calling through to the wrapped request object.
The HttpServletRequest provides methods for accessing parameters of a request. The type of the request determines where the parameters come from. In most implementations, a GET request takes the parameters from the query string, while a POST request takes the parameters from the posted arguments.
Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes − To intercept requests from a client before they access a resource at back end. To manipulate responses from server before they are sent back to the client.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With