【问题标题】:Wildcards in requestmapping请求映射中的通配符
【发布时间】:2013-06-12 15:40:43
【问题描述】:

我正在开发我的 Spring 应用程序,按照下面的代码,我将多个 URL 映射到一种方法。我正在制作一种“root”方法来服务所有以 index 和 root 开头的请求。

@RequestMapping(value = {"/", "index*"}, method = RequestMethod.GET)
public String root(Model model) {
    logger.info("Welcome to index page.");  
    model.addAttribute("hello", "Welcome to index page." );     
    return "index";
}

上述"index*""index", "index123", "index.html" and "index.txt" 的情况下工作正常,请求被定向到映射方法,即"root",但它不适用于"index.jsp"。如果是"index.jsp",我会收到"HTTP Status 404" "The requested resource is not available"

摘自web.xml

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

有人可以告诉我这背后的原因以及如何使它起作用吗?

【问题讨论】:

  • 我不想映射所有的 jsps,只想有一个 index* 类型请求的单一方法。
  • 在您的 web.xml 中,调度程序 servlet 是否映射为“/” url?
  • 是的,在我上面的问题中添加了来自web.xml 的摘录。

标签: java spring spring-mvc annotations http-status-code-404


【解决方案1】:

我认为这可能是因为 servlet 容器将 *.jsp 请求映射到 JspServlet 以便编译和执行 jsp。如果您使用的是 Tomcat,这会发生在 Tomcat 的 conf 目录中的顶级 web.xml 中。这意味着以 *.jsp 结尾的请求将在到达您的控制器之前被拦截。 JspServlet 将尝试根据 webapp 中的路径加载 index.jsp 文件,并在找不到时返回 404。

对于/index.jsp,您最好在 web 应用程序的根目录中实际创建此文件,这样您就不会看到 404。您可以在其中添加一些代码以将请求重定向到其他地方(可能是 @987654327 @ - 或应用程序的其他入口点)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-27
    • 2021-07-01
    • 2021-08-15
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2011-11-19
    • 2012-09-27
    相关资源
    最近更新 更多