1. 程式人生 > >[Java Web] 過濾器

[Java Web] 過濾器

value ole chain -name filter afa parameter tex javax

一、簡述

過濾器是服務端與客戶端的請求與響應的中間層組件,主要用戶對瀏覽器的請求進行過濾處理後再轉給下一個資源。

客戶端的請求在交給Servlet處理之前要經過FilterChain,服務端返回的響應也要經過FilterChain。FilterChain包含了多個Filter。

二、使用

FilterConfig是過濾器的配置對象,主要作用是獲取過濾器中的配置信息。

技術分享圖片
//MyFilter.java
package filter;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

public class MyFilter implements Filter { private FilterConfig config; private String addr; @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { String remote
= servletRequest.getRemoteAddr(); servletResponse.setCharacterEncoding("GB2312"); PrintWriter out = servletResponse.getWriter(); if (remote.equals(addr)) { out.println("request rejected: " + remote); } else { out.println("request accepted: " + remote); filterChain.doFilter(servletRequest, servletResponse); } } @Override
public void init(FilterConfig filterConfig) { config = filterConfig; addr = config.getInitParameter("addr"); } } //web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app> <filter> <filter-name>MyFilter</filter-name> <filter-class>filter.MyFilter</filter-class> <init-param> <param-name>addr</param-name> <param-value>127.0.0.1</param-value> </init-param> </filter> <filter-mapping> <filter-name>MyFilter</filter-name> <url-pattern>/*</url-pattern> <!-- 過濾所有請求 --> </filter-mapping> </web-app>
View Code

使用過濾器轉換字符編碼。

技術分享圖片
//MyFilter.java
package filter;

import javax.servlet.*;
import java.io.IOException;

public class MyFilter implements Filter {
    private boolean enable;
    private String encoding;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        if (enable) {
            servletRequest.setCharacterEncoding(encoding);
            servletResponse.setCharacterEncoding(encoding);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) {
        enable = Boolean.valueOf(filterConfig.getInitParameter("enable"));
        encoding = filterConfig.getInitParameter("encoding");
    }
}



//web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <filter>
        <filter-name>MyFilter</filter-name>
        <filter-class>filter.MyFilter</filter-class>
        <init-param>
            <param-name>enable</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>GB2312</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/*</url-pattern> <!-- 過濾所有請求 -->
    </filter-mapping>
</web-app>
View Code

[Java Web] 過濾器