如何从Java Filter获取请求URL?

我正试图编写一个filter,可以检索请求的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的正确方法是什么?

这是你在找什么?

 if (request instanceof HttpServletRequest) { String url = ((HttpServletRequest)request).getRequestURL().toString(); String queryString = ((HttpServletRequest)request).getQueryString(); } 

重build:

 System.out.println(url + "?" + queryString); 

HttpServletRequest.getRequestURL()HttpServletRequest.getQueryString()

 request.getRequestURL(); 
  • 文档

build立在此页面上的另一个答案 ,

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