如何从 JavaFilter 获得请求 URL?

我试图编写一个过滤器,可以检索请求的 URL,但我不知道如何做到这一点。

以下是我目前掌握的信息:

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() { }
}

当我点击服务器上的一个页面时,我看到的唯一输出是“ Url: null”。

从 Filter 中给定的 ServletRequest 对象获取请求的 URL 的正确方法是什么?

175398 次浏览
request.getRequestURL();

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

Building on another answer on this page,

public static String getCurrentUrlFromRequest(ServletRequest request)
{
if (! (request instanceof HttpServletRequest))
return null;


return getCurrentUrlFromRequest((HttpServletRequest)request);
}


public static String getCurrentUrlFromRequest(HttpServletRequest request)
{
StringBuffer requestURL = request.getRequestURL();
String queryString = request.getQueryString();


if (queryString == null)
return requestURL.toString();


return requestURL.append('?').append(queryString).toString();
}

If you use Spring, you can use OncePerRequestFilter or others.

import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.stereotype.Component;


@Component
public class MyFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String url = request.getRequestURL();
filterChain.doFilter(request, response);
}


}