servlet中url-pattern /与/* 的区别

 

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <display-name>contextLoaderListener</display-name>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--<init-param>-->
            <!--<param-name>contextConfigLocation</param-name>-->
            <!--<param-value>classpath:springMVC-servlet.xml</param-value>-->
        <!--</init-param>-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>
        

java类 Demo

@Controller
public class Demo {
    @RequestMapping("/test")
    public String test(){
        System.out.println("hehe");
        return "hehe";
    } 
}

WEB-INF下定义了hehe.jsp 显示hello world

启动tomcat,访问http://localhost:8080/test

报错,提示09-Jan-2018 15:44:37.805 WARNING [http-nio-8080-exec-6] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/WEB-INF/hehe.jsp] in DispatcherServlet with name 'springMVC'

查看别人资料,将

 <url-pattern>/*</url-pattern>
修改为
 <url-pattern>/</url-pattern>

发现可以正常访问:

 

原因分析:

根据前人所述,使用 /* 会导致返回的hehe.jsp再次进入DispatcherServlet,进而找不到与其匹配的路径,而通过错误提示可知路径为/WEB-INF/hehe.jsp,为了验证这个猜测,我在Demo类又加了一个与之对应的匹配

@Controller
public class Demo {
    @RequestMapping("/test")
    public String test(){
        System.out.println("hehe");
        return "hehe";
    }

    @RequestMapping("/WEB-INF/hehe.jsp")
    public String test2(){
        System.out.println("hehe2");
        return "hehe";
    }
}

以debug模式运行,发现果然进行了二次匹配~

 

如图,报错信息明显:循环路径


posted @ 2018-01-09 16:01  liuyuchong  阅读(396)  评论(0编辑  收藏  举报