一:什麼是過濾器 html
Filter:Servlet過濾器Fileter是一個小型的web組件,它們經過攔截請求和響應,以便查看、提取或以某種方式操做客戶端和服務器之間交換的數據,實現「過濾」的功能。Filter一般封裝了一些功能的web組件,過濾器提供了一種面向對象的模塊化機制,將任務封裝到一個可插入的組件中, Filter組件經過配置文件來聲明,並動態的代理。如其名字所暗示的同樣,Servlet過濾器用於攔截傳入的請求和傳出的響應,並監視、修改處理web工程中的數據流。過濾器是一個可插入的自由組件。web資源能夠不配置過濾器、也能夠配置單個過濾器,也能夠配置多個過濾器,造成一個過濾器鏈。Filter接受用戶的請求,並決定將請求轉發給鏈中的下一個組件,或者終止請求直接向客戶端返回一個響應。若是請求被轉發了,它將被傳遞給鏈中的下一個過濾器(以web.xml過濾器的配置順序爲標準)。這個請求在經過過濾鏈並被服務器處理以後,一個響應將以相反的順序經過該鏈發送回去。這樣,請求和響應都獲得了處理。java
二:利用過濾器統一設置編碼格式:web
在原來的servlet中,咱們須要爲每一個servlet設置請求編碼格式和響應編碼格式。若是我不設置編碼格式,就會變成這樣。服務器
但是若是servlet過多,咱們又須要改變編碼格式,這就很麻煩,因此就能夠利用過濾器來解決。模塊化
配置過濾器:編碼
自定義過濾器類:代理
public class myFilter implements Filter { private String encode; /** * Default constructor. */ public myFilter() { // TODO Auto-generated constructor stub } /** * @see Filter#destroy() */ public void destroy() { // TODO Auto-generated method stub } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub // place your code here // pass the request along the filter chain System.out.println("此時的encode爲"+encode); request.setCharacterEncoding(encode); String respCoding="text/html;charset="+encode; response.setContentType(respCoding); chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { // TODO Auto-generated method stub System.out.println("執行初始化"); encode=fConfig.getInitParameter("charset"); System.out.println(encode); } }
運行結果:code
輸入用戶張三:xml