web.xml中/和/*的差別
- < url-pattern>/ 會比對到/login這樣的路徑型url,不會比對到模式為*.jsp這樣的字尾型url
-
< url-pattern>/* 會比對所有url:路徑型的和字尾型的url(包括/login,*.jsp,*.js和*.html等)
因為 springmvc 要使用DispatcherServlet類 處理 前端的 請求,是以配置為< url-pattern > / </ url-pattern > 将路徑型url 交給springMVC處理
例如 中文亂碼處理、shiro 安全認證處理需要處理所有的 url ,是以配置為< url-pattern > /* </ url-pattern >
< url-pattern > / </ url-pattern > 不會比對到*.jsp,即:*.jsp不會進入spring的 DispatcherServlet類 。
< url-pattern > /* </ url-pattern > 會比對*.jsp,會出現傳回jsp視圖時再次進入spring的DispatcherServlet 類,導緻找不到對應的controller是以報404錯。
例某 web.xml檔案配置:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
3 <!-- 配置spring 上下文參數 -->
4 <context-param>
5 <param-name>contextConfigLocation</param-name>
6 <param-value>classpath:applicationContext.xml</param-value>
7 </context-param>
8 <!-- 配置spring ---- 配置偵聽器 -->
9 <listener>
10 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
11 </listener>
12 <!-- 配置springmvc 核心控制器 -->
13 <servlet>
14 <servlet-name>springDispatcherServlet</servlet-name>
15 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
16 <init-param>
17 <param-name>contextConfigLocation</param-name>
18 <param-value>classpath:springMVC.xml</param-value>
19 </init-param>
20 <load-on-startup>1</load-on-startup>
21 </servlet>
22 <servlet-mapping>
23 <servlet-name>springDispatcherServlet</servlet-name>
24 <url-pattern>/</url-pattern>
25 </servlet-mapping>
26 <!-- 配置shiro認證過濾器 -->
27 <filter>
28 <filter-name>shiroFilter</filter-name>
29 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
30 <init-param>
31 <param-name>targetFilterLifecycle</param-name>
32 <param-value>true</param-value>
33 </init-param>
34 </filter>
35 <filter-mapping>
36 <filter-name>shiroFilter</filter-name>
37 <url-pattern>/*</url-pattern>
38 </filter-mapping>
39 <!-- 配置編碼過濾器(隻對post方法) -->
40 <filter>
41 <filter-name>CharacterEncodingFilter</filter-name>
42 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
43 <init-param>
44 <param-name>encoding</param-name>
45 <param-value>UTF-8</param-value>
46 </init-param>
47 <init-param>
48 <param-name>forceRequestEncoding</param-name>
49 <param-value>true</param-value>
50 </init-param>
51 <init-param>
52 <param-name>forceResponseEncoding</param-name>
53 <param-value>true</param-value>
54 </init-param>
55 </filter>
56 <filter-mapping>
57 <filter-name>CharacterEncodingFilter</filter-name>
58 <url-pattern>/*</url-pattern>
59 </filter-mapping>
60 </web-app>