【问题标题】:URL pattern servlet mappingURL 模式 servlet 映射
【发布时间】:2017-03-27 01:08:05
【问题描述】:

我使用 Spring MVC 创建了 hello world 示例,但是在 servlet URL 映射中有一点我不明白,我在 web.xml 中做了以下操作:

<servlet>
    <servlet-name>HelloWeb</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>HelloWeb</servlet-name>
    <url-pattern>/test/*</url-pattern>
</servlet-mapping>

现在如果我想调用以下控制器:

@Controller
@RequestMapping("/hello")
public class HelloWorld {
    @RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap model){
        model.addAttribute("message","hello world");
        return "index";
    }
}

它将使用以下链接工作: http://localhost:8080/test/hello

但是当我将 servlet url-pattern 更改为“/*”并尝试: http://localhost:8080/hello

它不起作用,它不应该与我的 servlet 匹配吗?因为 * 匹配所有内容

【问题讨论】:

    标签: spring-mvc servlets


    【解决方案1】:

    当您使用“/*”注册 servlet 时,它将覆盖所有 servlet 映射(如果有)。因此应该避免。这也会覆盖默认的 servlet 映射,因此所有默认的 url 处理也会被覆盖,因此任何特定的 url 匹配都会失败。在您的情况下,它是 /hello。

    对于您的案例,最初您使用 /test/* 注册,这会将您的所有 URL 注册到 /test,因此它们被识别。

    【讨论】:

      【解决方案2】:

      它不适用于/*,因为您还没有为该模式注册/创建控制器。

      它适用于http://localhost:8080/hello,因为你有控制器@RequestMapping("/hello")

      只需将 RequestMapping 更改为 @RequestMapping("/") for url-pattern /*

      【讨论】:

      猜你喜欢
      • 2011-05-12
      • 2011-02-24
      • 1970-01-01
      • 2010-10-04
      • 2019-03-06
      • 2012-01-20
      • 2017-09-21
      • 1970-01-01
      • 2015-07-28
      相关资源
      最近更新 更多