1. 程式人生 > >Filter (攔截器)

Filter (攔截器)

一、Filter簡介

Filter也稱之為過濾器,它是Servlet技術中最激動人心的技術之一,WEB開發人員通過Filter技術,
對web伺服器管理的所有web資源:例如Jsp,
Servlet, 靜態圖片檔案或靜態html檔案等進行攔截,
從而實現一些特殊的功能。例如實現URL級別的許可權訪問控制、過濾敏感詞彙、壓縮響應資訊等
一些高階功能。

Filter介面中有一個doFilter方法,當我們編寫好Filter,並配置對哪個web資源進行攔截後,WEB伺服器每次在呼叫web資源之前,
都會先呼叫一下filter的doFilter方法,
因此,在該方法內編寫程式碼可達到如下目的:
?
是否放行該資源:方法內部呼叫 chain.doFilter(request, response);

二、過濾器案例實現
許可權控制
某個使用者直到了內部的一些url 直接通過訪問url就可以獲取結果 過濾器防止這種情況
統一的字符集設定
過濾器攔截所有資源 統一設定字符集和編碼
作業:
過濾敏感詞彙
新建 a.html 新增文字域(textarea) 過濾器進行過濾 如果輸入內容有 傻逼 SB等等這個特殊字 跳轉到頁面顯示 您輸入了敏感詞
壓縮響應(選做 util.gzip壓縮)
攔截 jpg png gif 結尾 將檔案使用zip壓縮 並且告訴瀏覽器 我是zip壓縮的(響應頭) 瀏覽自動解壓
response.setHeader(“Content-Encoding”, “gzip”);
三 監聽器
監聽器 兩大類 生命週期監聽器和資料變化監聽器

生命週期監聽器

request 訪問時產生請求物件 響應後銷燬 實現ServletRequestListener介面
session 呼叫getSession()方法時產生session 超時後自動銷燬 實現 HttpSessionListener
servletcontext 在容器啟動時產生 容器關閉或者重新載入時銷燬 實現ServletContextListener

統計多少臺機器訪問了我的頁面

資料變化監聽器
request 當呼叫setAtrribite(“id”,“1”) 觸發add事件 setAtrribite(“id”,“2”) 觸發replace事件 removeAtrribute(“id”) 觸發remove事件
session 當呼叫setAtrribite(“id”,“1”) 觸發add事件 setAtrribite(“id”,“2”) 觸發replace事件 removeAtrribute(“id”) 觸發remove事件
servletcontext

package com.uploading;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;

@WebServlet(urlPatterns= {"/fileUpls"})
public class FileSystem2 extends HttpServlet {
	/**
	 * 檔案上傳
	 */
	private static final long serialVersionUID = 1L;
	static final String  filePath = "D:\\addFile\\";
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding("UTF-8");
		//處理Multipart編碼格式的資料
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		if(isMultipart) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			//解決中文亂碼問題
			upload.setHeaderEncoding("UTF-8");
			try {
				List<FileItem> items = upload.parseRequest(req);
				for (FileItem fileItem : items) {
					if(!fileItem.isFormField()) {
						//檔案
						String fileValue=fileItem.getName();//上傳的檔名
						
						//獲取檔案的字尾名
						String extension = FilenameUtils.getExtension(fileValue);
						//獲取32隨機位字串
						String str= UUID.randomUUID().toString();
						this.getServletContext().setAttribute(str, fileValue);
						
						resp.getWriter().println("你的下載提取碼是:"+str);
						InputStream inputStream = fileItem.getInputStream();
						String fileData=filePath+str+"."+extension;
						FileOutputStream fileOutputStream = new FileOutputStream(fileData);
						IOUtils.copy(inputStream, fileOutputStream);
						fileOutputStream.close();
						inputStream.close();
					}
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
}

package com.uploading;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

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

import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
@WebServlet(urlPatterns= {"/fileDows"})
public class FileDow2 extends HttpServlet {
/**
* 檔案下載
*/
static final String filePath = “D:\addFile\”;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType(“text/html;charset=UTF-8”);
resp.setCharacterEncoding(“UTF-8”);
req.setCharacterEncoding(“UTF-8”);

	String ext = req.getParameter("extract");
	Object attribute = this.getServletContext().getAttribute(ext);
	if(attribute==null) {
		resp.getWriter().println("<p color='red'>上傳的檔案不存在");
		return;
	}
	String fileName=filePath+ext+"."+FilenameUtils.getExtension(attribute.toString());
	
	//告訴瀏覽器下載的檔名  設定響應頭
	resp.setContentType("text/plain");
	resp.setHeader("Location", attribute.toString());
	resp.setHeader("Content-Disposition", "attachment; fileName="+attribute.toString());
	FileInputStream fileInputStream = new FileInputStream(fileName);
	//將檔案內容寫入響應
	IOUtils.copy(fileInputStream, resp.getOutputStream());
	
	
	
}

}

package com.test4.listeners;



import javax.servlet.annotation.WebListener;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;
/**
 * 生命週期監聽器
 * @author Administrator
 *
 */
@WebListener
public class SessionLis implements HttpSessionListener {
	/**
	 * 當某個身份號被建立
	 */
	static int flag=0;
	@Override
	public void sessionCreated(HttpSessionEvent se) {
			flag++;
			HttpSession session = se.getSession();
			System.out.println(session.getId()+"被建立了");
			System.out.println("訪問的使用者"+flag+"個");
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		HttpSession session = se.getSession();
		System.out.println(session.getId()+"被銷燬了");
		
	}

	

	

	

}