【问题标题】:Spring MVC RequestMapping requires trailing slashSpring MVC RequestMapping 需要尾部斜杠
【发布时间】:2020-05-11 20:58:49
【问题描述】:

似乎有一些奇怪的行为,我似乎无法确定原因。当我访问特定的 url 时,我会收到 404 响应,而由同一控​​制器类处理的其他 url 可以正常工作。我必须在 url 的末尾添加一个尾随 / 才能调用该方法。

访问 localhost:8080/newprofile 时不会调用此方法

 @RequestMapping(value="/newprofile", method=RequestMethod.GET)
    public String newProfile(Model model, Principal principal) {
        return "newprofile";
    }

但是,在访问 localhost:8080/login 时会调用这个函数

@GetMapping("/login")
public String login() {
    return "login";
}

我已经尝试过 GetMapping 和 RequestMapping,但这些方法从未被调用过。

这两种方法都包含在我的控制器类中

    @Controller
    public class HomeResources {
    //login
    //new profile
        }

【问题讨论】:

    标签: java spring spring-boot spring-mvc


    【解决方案1】:

    有一个设置负责这种行为:

    https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.html#setUseTrailingSlashMatch-boolean-

    把它关掉:

    @Configuration
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
    
      @Override
      public void configurePathMatch(PathMatchConfigurer configurer) {
          configurer.setUseTrailingSlashMatch(false);
      }
    }
    

    【讨论】:

    • 要理解,true 应该同时匹配 /newprofile/newprofile/ 对吧?
    • 是的,所以这只是您的问题的一部分。最好打开详细的 Spring 日志记录并检查从请求到响应的整个过程。
    • @AlexChernyshev 如果默认设置应该两者都匹配,那么禁用它应该如何解决问题?看起来无关紧要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    相关资源
    最近更新 更多