過濾器過濾一個包內所有servlet,先看下文件的目錄結構:
我們要做的就是用MyFirstFilter過濾servlet包內的所有servlet即DisplayHeader、HelloServlet、SecondServlet。
主要就是兩個注意事項:
1:
這裡一定要注意就是那個注釋部分:
它原來的值是:@WebServlet(“/HelloServlet”),一定要改成上圖所示的才可以
2.就是web.xml了,代碼如下所示:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 <!--?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"> <filter> <filter-name>MyFirstFilter</filter-name> <filter-class>com.util.MyFirstFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>GBK</param-value> </init-param> <init-param> <param-name>secondAttribute</param-name> <param-value>filterConfig的第二個參數</param-value> </init-param> </filter> <filter-mapping> <filter-name>MyFirstFilter</filter-name> <url-pattern>/servlet/*</url-pattern> <url-pattern>/checkIn.jsp</url-pattern> </filter-mapping> <servlet> <!-- 類名 --> <servlet-name>HelloServlet</servlet-name> <!-- 所在的包 --> <servlet-class>servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <!-- 訪問的網址 --> <url-pattern>/SummerTest/servlet/HelloServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>SecondServlet</servlet-name> <servlet-class>servlet.SecondServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SecondServlet</servlet-name> <!-- 訪問的網址 --> <url-pattern>/SummerTest/servlet/SecondServlet</url-pattern> </servlet-mapping> <servlet> <!-- 類名 --> <servlet-name>DisplayHeader</servlet-name> <!-- 所在的包 --> <servlet-class>servlet.DisplayHeader</servlet-class> </servlet> <servlet-mapping> <servlet-name>DisplayHeader</servlet-name> <!-- 訪問的網址 --> <url-pattern>/SummerTest/servlet/DisplayHeader</url-pattern> </servlet-mapping> </web-app>
注意這兩個地方應該就可以達到目的了。