天天看點

測試web頁面下的過濾器

1.建立一個FirstFilter類,代碼如下:

package com.ask.filter;
 import java.io.IOException;
 import javax.servlet.Filter;
 import javax.servlet.FilterChain;
 import javax.servlet.FilterConfig;
 import javax.servlet.ServletException;
 import javax.servlet.ServletRequest;
 import javax.servlet.ServletResponse;
 /*自定義一個java類實作filter接口*/
 public class FirstFilter implements Filter {
 public FirstFilter(){
 System.out.println("FirstFilter: "+this.hashCode());
 }
 public void init(FilterConfig arg0) throws ServletException {
 System.out.println("init: "+this.hashCode());
 }
 public void doFilter(ServletRequest req, ServletResponse res,
 FilterChain chain) throws IOException, ServletException {
 System.out.println("doFilter: "+this.hashCode());
 //調用下一個filter或者是web資源
 //chain.doFilter(req, res);
 }
 public void destroy() {
 System.out.println("destroy: "+this.hashCode());
 }
 }      

2.建立一個web端顯示的頁面showServlet類,代碼如下:

package com.ask.filter;
 import java.io.IOException;
 import javax.servlet.Filter;
 import javax.servlet.FilterChain;
 import javax.servlet.FilterConfig;
 import javax.servlet.ServletException;
 import javax.servlet.ServletRequest;
 import javax.servlet.ServletResponse;
 /*自定義一個java類實作filter接口*/
 public class FirstFilter implements Filter {
 public FirstFilter(){
 System.out.println("FirstFilter: "+this.hashCode());
 }
 public void init(FilterConfig arg0) throws ServletException {
 System.out.println("init: "+this.hashCode());
 }
 public void doFilter(ServletRequest req, ServletResponse res,
 FilterChain chain) throws IOException, ServletException {
 System.out.println("doFilter: "+this.hashCode());
 //調用下一個filter或者是web資源
 //chain.doFilter(req, res);
 }
 public void destroy() {
 System.out.println("destroy: "+this.hashCode());
 }
 }      

3.web.xml配置檔案如下:

<?xml version="1.0" encoding="UTF-8"?>
 <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">
 <display-name>firstServlet</display-name>
 <welcome-file-list>
 <welcome-file>index.html</welcome-file>
 <welcome-file>index.htm</welcome-file>
 <welcome-file>index.jsp</welcome-file>
 <welcome-file>default.html</welcome-file>
 <welcome-file>default.htm</welcome-file>
 <welcome-file>default.jsp</welcome-file>
 </welcome-file-list>
 <filter>
 <filter-name>first</filter-name>
 <filter-class>com.ask.filter.FirstFilter</filter-class>
 </filter>
 <filter-mapping>
 <filter-name>first</filter-name>
 <url-pattern>/show</url-pattern>
 </filter-mapping>
 <servlet>
 <servlet-name>show</servlet-name>
 <servlet-class>com.ask.servlet.showServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>show</servlet-name>
 <url-pattern>/show</url-pattern>
 </servlet-mapping>
 </web-app>