<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>eShop</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置字符過濾器 --> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <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> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
其中/和/*的區別:
< url-pattern > / </ url-pattern > 不會匹配到*.jsp,即:*.jsp不會進入spring的 DispatcherServlet類 。
< url-pattern > /* </ url-pattern > 會匹配*.jsp,會出現返回jsp視圖時再次進入spring的DispatcherServlet 類,導致找不到對應的controller所以報404錯。
總之,關於web.xml的url映射的小知識:
< url-pattern>/</url-pattern> 會匹配到/login這樣的路徑型url,不會匹配到模式為*.jsp這樣的后綴型url
< url-pattern>/*</url-pattern> 會匹配所有url:路徑型的和后綴型的url(包括/login,*.jsp,*.js和*.html等)
1. 首先/這個是表示默認的路徑,及表示:當沒有找到可以匹配的URL就用這個URL去匹配。 2. 在springmvc中可以配置多個DispatcherServlet,比如: 配置多個DispatcherServlet有/和/*,先匹配的是/*這個 3. 當配置相同的情況下,DispathcherServlet配置成/和/*的區別 <一> /:使用/配置路徑,直接訪問到jsp,不經springDispatcherServlet <二> /*:配置/*路徑,不能訪問到多視圖的jsp 當我在客戶端調用URL:/user/list然后返回user.jsp視圖,當配置的是/:DispathcherServlet拿到這個請求然后返回對應的controller, 然后依據Dispather Type為Forward類型轉發到user.jsp視圖,即就是請求user.jsp視圖(/user/user.jsp),此時Dispather沒有攔截/user/user.jsp, 因為此時你配置的是默認的/,就順利的交給ModleAndView去處理顯示了。 當配置的是/*:DispathcherServlet拿到這個請求然后返回對應的controller,然后通過Dispather Type通過Forward轉發到user.jsp視圖, 即就是請求user.jsp視圖(/user/user.jsp),此時Dispather已經攔截/user/user.jsp,Dispatcher會把他當作Controller去匹配,沒有匹配到就會報404錯誤。 結論:/ 能匹配路徑型URL,不能匹配后綴型URL /* 能匹配任何類型URL,在配置視圖的時候盡量用/這種方式。