spring引导请求到上下文路径/为静态内容生成405方法不允许错误



我有一个带有上下文路径/服务的spring-boot应用程序。属性文件中的上下文路径条目:

server.servlet.context-path=/services

当我使用URL时http://localhost:8080/services/使用GET方法,它运行良好,并返回静态index.html文件作为响应。但是当我尝试使用相同的URL时http://localhost:8080/services/使用POST方法,我得到以下错误:

{
"timestamp": "2020-11-11T07:06:37.341+00:00",
"status": 405,
"error": "Method Not Allowed",
"message": "",
"path": "/services/"
}

我尝试过使用重定向上下文根属性,但这并没有帮助。我还尝试了server.servlet.context path=/services/-,但这也没有帮助。什么属性或配置将强制spring框架允许POST方法用于任何带有尾部斜杠(/(的上下文路径的请求?

从日志中,我可以看到视图被解析为[view="forward:index.html"],但紧接着我们看到ERROR HttpRequestMethodNotSupportedException:不支持请求方法'POST'。所以不能理解哪个spring类导致了这个错误?我们如何才能抑制这种行为?

o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/rest/**']
o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/'; against '/rest/**'
o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
o.s.web.servlet.DispatcherServlet        : POST "/services/", parameters={}
pertySourcedRequestMappingHandlerMapping : looking up handler for path: /
o.s.b.a.w.s.WelcomePageHandlerMapping    : Mapped to ParameterizableViewController [view="forward:index.html"]
o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@363fa5d2
w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
o.s.web.servlet.DispatcherServlet        : Completed 405 METHOD_NOT_ALLOWED

报告了一个春季问题:https://github.com/spring-projects/spring-framework/issues/22140.但spring也明确表示,他们不会做出任何这样的更改,因为对静态资源的请求不应该是POST类型,因为我们并没有试图修改它们,而是试图获取它们。

我一直在寻找一个变通方法,因为我必须在上下文根支持POST(因为SSO-IDP的要求(。因此,我尝试在Filter中复制302重定向行为。在其中一个过滤器中,我检查了请求方法POST、请求URI/services/,并将请求重定向到/services/。这将POST请求转换为路径/services/上的GET,并且可以正常工作。

// Inside doFilter() method of a Filter
if ("POST".equalsIgnoreCase(httpRequest.getMethod()) && "/services/".equalsIgnoreCase(httpRequest.getRequestURI())) {
httpResponse.sendRedirect("/services/"); // This converts the POST request to GET request
return;
}

在过滤器中引入此行为后,当我将请求POST到http://localhost:8080/services/,从上面的过滤器中,它被重定向到http://localhost:8080/services/使用GET方法,我得到了所需的index.html作为响应。

最新更新