【问题标题】:Force 404 error when extension is added to URL将扩展名添加到 URL 时强制 404 错误
【发布时间】:2015-12-21 16:35:39
【问题描述】:

我需要一些有关 URL 映射的帮助,在我的代码中:

http://localhost:8080/register.asdf
http://localhost:8080/register.asddsdsd etc.

它总是返回http://localhost:8080/register,但我想让它404 NOT FOUND
我该如何解决这个问题?

public class WebInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext servletContext) throws ServletException {    
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();  
    ctx.register(Config.class);  
    ctx.setServletContext(servletContext);    
    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));  
    servlet.addMapping("/");  
    servlet.setLoadOnStartup(1);
}

}

@Controller
public class UserController {

@RequestMapping(path = "/register", method = RequestMethod.GET)
public String registerGet(Model model) {

    return "register";
}

编辑:我在 Config.java 中添加了以下代码并解决了谢谢。

@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
    configurer.setUseSuffixPatternMatch(false);
}

【问题讨论】:

    标签: spring spring-mvc http-status-code-404 url-mapping


    【解决方案1】:

    您可以在@RequestMappingservlet.mapping 中限制映射更改。 更改请求映射:

    @RequestMapping(path = "/register.htm", method = RequestMethod.GET)//for example  
    

    或servlet.mapping:

    servlet.addMapping("*.htm");  
    

    编辑: 如果您使用的是 Spring 4.X,则可以使用:

    <mvc:annotation-driven>
        <mvc:path-matching suffix-pattern="false" />
    </mvc:annotation-driven>
    

    【讨论】:

    • 还有没有插入扩展的?
    【解决方案2】:

    来自docs 使用下面的配置来限制不需要的扩展

    <mvc:annotation-driven>
        <mvc:path-matching suffix-pattern="false" />
    </mvc:annotation-driven>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-24
      • 2022-01-25
      • 2015-08-10
      • 2010-12-14
      • 1970-01-01
      • 2018-04-09
      • 2016-07-30
      • 2011-09-05
      相关资源
      最近更新 更多