gpt4 book ai didi

spring - request.getServletPath() 从 Spring MVC 返回 null

转载 作者:行者123 更新时间:2023-12-05 00:49:03 24 4
gpt4 key购买 nike

我做了一个过滤器来从所有请求中捕获 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 没有映射到它的 Controller 或 View

<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 而不是?

最佳答案

你得到 null 因为

request.getServletPath();

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

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

更多信息为什么:

How to get request URI without context path?

关于spring - request.getServletPath() 从 Spring MVC 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46592664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com