Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the request URL from a Java Filter?

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?

like image 604
ampersandre Avatar asked Dec 08 '10 16:12

ampersandre


People also ask

What is filter request?

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.

What is the use of HttpServletRequestWrapper?

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.

What is HTTP servlet request?

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.

What is servlet filter?

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.


1 Answers

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().

like image 194
Buhake Sindi Avatar answered Oct 21 '22 02:10

Buhake Sindi