Sping MVC URL 根路径匹配的困惑

 

项目中用到了Spring MVC,需要匹配根路径,那RequestMapping我该写啥?

 

@RequestMapping("")  还是  @RequestMapping("/")

 

结果发现都能匹配,更仔细地测试:

 

@Controller
public class MappingTest {

    @RequestMapping("/")
    @ResponseBody
    public String index(){
        return "index";
    }

    @RequestMapping("/second")
    @ResponseBody
    public String secondLevel(){
        return "second";
    }
}

 用例:

http://localhost:8080/second ok

http://localhost:8080/second?age=10 ok
http://localhost:8080//second ok

 

http://localhost:8080/second/ ok
http://localhost:8080/second/?age=10  ok

http://localhost:8080/second?age=10  ok

 

发现上述路径全都能匹配。Spring MVC 匹配路径的规则同Ant Path Matcher ,因此推测结论: 

    Ant 在处理url的时候对于中间多余的"/" 和尾部的"/" 都会被忽略。

 

 

那么Servlet 本身URL匹配也是这样的规则吗? 又创建以下测试:

 

    <servlet>
        <servlet-name>second</servlet-name>
        <servlet-class>dan.controller.Second</servlet-class>
    </servlet>

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

 

 

public class Second extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("second - from servlet");
    }
}
 

 

发现:

 

http://localhost:8080/second ok
http://localhost:8080/second?age=10 ok
http://localhost:8080//second ok

http://localhost:8080/second/ 404
http://localhost:8080/second/?age=10  404

对于中间多余的"/",Servlet url-pattern匹配同Ant Path 处理的情况,但是对于尾部的 "/",Servlet url-pattern认为*/ 和 * 是不同的情况。

 

上述测试仅仅是在Tomcat7环境下做的测试,不保证其它servlet容器也符合这一规则。

 

附:

AntPathMatcher 

http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/AntPathMatcher.html

Servlet url-pattern

http://www.roguewave.com/portals/0/products/hydraexpress/docs/3.5.0/html/rwsfservletug/4-3.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值