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

时间:2010-12-08 16:09:05

标签: java url servlet-filters

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

4 个答案:

答案 0 :(得分:151)

这是你要找的吗?

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

重建:

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

HttpServletRequest.getRequestURL()HttpServletRequest.getQueryString()上的信息。

答案 1 :(得分:2)

request.getRequestURL();   

答案 2 :(得分:1)

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

答案 3 :(得分:1)

如果您使用 Spring,则可以使用 OncePerRequestFilter 或其他。

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

}