1. 程式人生 > >過濾器簡介--學習筆記

過濾器簡介--學習筆記

過濾器簡介--學習筆記

a)Filter是SUN公司提供的一個資源過濾器接口,不同的Web容器有著不同的實現
b)Filter位於Web服務器和Web資源(Servlet/Jsp/Html)之間
c)過濾請求和響應二者
d)Filter可以進行簡單判段,是否將請求放行給Web資源
e)Filter的開發過程:

>類 implements javax.servlet.Filter接口
>在web.xml文件配置Filter過濾器,告之Web服務器有過濾器的存在
web.xml中的配置信息如下:
<filter>
<filter-name>FilterDemo1</filter-name>(過濾器,可以隨意,但要和filter-mapping中的name一致)

<filter-class>cn.web.filter.FilterDemo1</filter-class>(過濾器全路徑)
</filter>
<filter-mapping>
<filter-name>FilterDemo1</filter-name>(過濾器名,同上)
<url-pattern>/*</url-pattern>(過濾器能夠過濾的資源路徑,不是用戶在URL中訪問的路徑)
</filter-mapping>

技術分享圖片

ShowServlet

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShowServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("test/html; charset=UTF-8");
        response.getWriter().write("歡迎學習servlet下篇");

    }

}

FilterDemo1

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;

//自定義Filter過渡器
public class FilterDemo1 implements Filter {
    public void destroy() {
    }
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {

        System.out.println("過濾器+++doFilter()");
        //放行請求[類似於函數調用]
        chain.doFilter(request,response);
        System.out.println("放行請求[類似於函數調用]");

    }
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
    <filter>
        <filter-name>FilterDemo1</filter-name>
        <filter-class>cn.web.servlet.filter.FilterDemo1</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>FilterDemo1</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    </web-app>

技術分享圖片

過濾器簡介--學習筆記