如何从 Java 过滤器获取请求 URL?

2022-08-31 11:29:43

我正在尝试编写一个可以检索请求 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”。

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


答案 1

这是你要找的吗?

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

要重建:

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

有关 HttpServletRequest.getRequestURL()HttpServletRequest.getQueryString() 的信息


答案 2

基于此页面上的另一个答案

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