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?age=10 ok
http://localhost:8080//////second ok
http://localhost:8080/second/ 404
http://localhost:8080/second/?age=10 404
上述测试仅仅是在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