【问题标题】:request.getServletPath() returned null from Spring MVCrequest.getServletPath() 从 Spring MVC 返回 null
【发布时间】:2018-03-17 11:43:14
【问题描述】:

我做了一个过滤器来从所有请求中捕获HttpServletRequest sevlet 路径

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest)req;
    HttpServletResponse response = (HttpServletResponse)res;

    // debug to see the output
    String path = request.getServletPath();

    filterChain.doFilter(request, response);
}

jsp 中有一个 URL 没有映射到它的控制器或视图

<div>
    <spring:url value="/app" var="app_url" htmlEscape="true"/>
    <a href="${app_url}"><spring:message code="label_3rd_app" /></a>
</div>

但是,当在过滤器上调试时单击 url,我看到来自两个请求的 request.getServletPath() 值:

/null
/null/app

我的问题是为什么request.getServletPath() 永远不会返回/app

【问题讨论】:

    标签: spring jsp spring-mvc


    【解决方案1】:

    你得到 null 因为

    request.getServletPath();
    

    适用于 Servlet,您在过滤器中执行此操作。要在过滤器中获取它,您必须像这样手动构建它:

    HttpServletRequest request = (HttpServletRequest) req;
    String path = request.getRequestURI().substring(request.getContextPath().length());
    

    更多信息为什么:

    How to get request URI without context path?

    【讨论】:

    • 这不是等效的解决方案。 getServletPath() 返回 uri 解码路径“/servlet path/foo”,而 getRequestURI() 返回 uri 编码路径“/context/servlet%20path/foo”。
    【解决方案2】:

    先生。 Lalibertes 解决方案无法正常工作,因为getRequestURI 是uri-encoded 而getServletPath 不是。

    在这种情况下,最好使用 Springs UrlPathHelper 来获取 servlet 路径。

    new org.springframework.web.util.UrlPathHelper().getPathWithinApplication(servletRequest);
    

    此方法提供经过 uri 解码的 servlet 路径,如 getServletPath 所具有的 - 如果它不是 null

    【讨论】:

      【解决方案3】:

      对于仅仅因为您的上下文路径为空而提出这个问题的人(比如我):我在后台线程中调用 request.getContextPath()

      如果我正确理解了这个错误报告讨论,那么请求就会“超出范围”:https://bugs.eclipse.org/bugs/show_bug.cgi?id=401768

      另外,我知道我不应该在 servlet 环境中使用普通线程,而是使用Executor。但问题可能仍然存在:https://developer.jboss.org/thread/232135

      解决方案是在移交给后台线程之前从请求中提取所有需要的信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-26
        • 1970-01-01
        • 2018-07-27
        • 1970-01-01
        • 1970-01-01
        • 2016-01-08
        • 1970-01-01
        • 2013-11-27
        相关资源
        最近更新 更多