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

本文探讨了Spring MVC中URL映射导致的问题及解决方法。当使用'/*'作为DispatcherServlet的URL映射时,可能会导致视图解析错误。通过调整为'/',解决了视图无法正确解析的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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模式运行,发现果然进行了二次匹配~

 

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


转载于:https://www.cnblogs.com/liuyuchong/p/8251867.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值