filter過濾器主要使用於前臺向後臺傳遞資料是的過濾操作。程度很簡單就不說明了,直接給幾個已經寫好的程式碼:
一、使瀏覽器不快取頁面的過濾器
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
* 用於的使 Browser 不快取頁面的過濾器
*/
public class ForceNoCacheFilter implements Filter {
{
((HttpServletResponse) response).setHeader("Cache-Control","no-cache");
((HttpServletResponse) response).setHeader("Pragma","no-cache");
((HttpServletResponse) response).setDateHeader ("Expires", -1);
filterChain.doFilter(request, response);
}
{
}
{
}
}
- import javax.servlet.*;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import java.util.List;
- import java.util.ArrayList;
- import java.util.StringTokenizer;
- import java.io.IOException;
- /**
- * 用於檢測使用者是否登陸的過濾器,如果未登入,則重定向到指的登入頁面<p>
- * 配置引數<p>
- * checkSessionKey 需檢查的在 Session 中儲存的關鍵字<br/>
- * redirectURL 如果使用者未登入,則重定向到指定的頁面,URL不包括 ContextPath<br/>
- * notCheckURLList 不做檢查的URL列表,以分號分開,並且 URL 中不包括 ContextPath<br/>
- */
- public class CheckLoginFilter
- implements Filter
- {
- protected FilterConfig filterConfig = null;
- private String redirectURL = null;
- private List notCheckURLList = new ArrayList();
- private String sessionKey = null;
- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
- {
- HttpServletRequest request = (HttpServletRequest) servletRequest;
- HttpServletResponse response = (HttpServletResponse) servletResponse;
- HttpSession session = request.getSession();
- if(sessionKey == null)
- {
- filterChain.doFilter(request, response);
- return;
- }
- if((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null)
- {
- response.sendRedirect(request.getContextPath() + redirectURL);
- return;
- }
- filterChain.doFilter(servletRequest, servletResponse);
- }
- public void destroy()
- {
- notCheckURLList.clear();
- }
- private boolean checkRequestURIIntNotFilterList(HttpServletRequest request)
- {
- String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
- return notCheckURLList.contains(uri);
- }
- public void init(FilterConfig filterConfig) throws ServletException
- {
- this.filterConfig = filterConfig;
- redirectURL = filterConfig.getInitParameter("redirectURL");
- sessionKey = filterConfig.getInitParameter("checkSessionKey");
- String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList");
- if(notCheckURLListStr != null)
- {
- StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");
- notCheckURLList.clear();
- while(st.hasMoreTokens())
- {
- notCheckURLList.add(st.nextToken());
- }
- }
- }
- }
三、字元編碼的過濾器
- import javax.servlet.*;
- import java.io.IOException;
- /**
- * 用於設定 HTTP 請求字元編碼的過濾器,通過過濾器引數encoding指明使用何種字元編碼,用於處理Html Form請求引數的中文問題
- */
- public class CharacterEncodingFilter
- implements Filter
- {
- protected FilterConfig filterConfig = null;
- protected String encoding = "";
- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
- {
- if(encoding != null)
- servletRequest.setCharacterEncoding(encoding);
- filterChain.doFilter(servletRequest, servletResponse);
- }
- public void destroy()
- {
- filterConfig = null;
- encoding = null;
- }
- public void init(FilterConfig filterConfig) throws ServletException
- {
- this.filterConfig = filterConfig;
- this.encoding = filterConfig.getInitParameter("encoding");
- }
- }
四、記錄使用者的訪問操作器
程式碼:
package com.qwserv.itm.pfl.log.svr;
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;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import com.qwserv.itm.api.pfl.sm.vo.Person;
import java.sql.*;
import com.qwserv.itm.api.ServiceAccess;
import com.qwserv.itm.util.toolkit.DebugUtil;
public class ObserveFilter implements Filter {
protected static DebugUtil log = DebugUtil.getInstances("pfl-log", ObserveFilter.class);
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
//記錄使用者的訪問操作
HttpServletRequest request1 = (HttpServletRequest)request;
StringBuffer url = request1.getRequestURL();
//對url進行過濾,如果是js/css/image則不進行處理
if (judgeFile(url.toString())){
String operTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
format(new java.util.Date());
String hostIp = request.getRemoteAddr();
String sessionId = request1.getRequestedSessionId();
String userId = "";
Person person = (Person)request1.getSession().getAttribute("userObj");
if (null != person && null != person.getUser()){
userId = person.getUser().getId();
}
String queryString = request1.getQueryString();
if (null != queryString) {
url.append('?');
url.append(queryString);
}
//儲存到資料庫中
saveToDb(userId,hostIp,sessionId,url.toString(),operTime,"");
}
// Pass control on to the next filter
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
}
public boolean judgeFile(String url){
if (url.endsWith(".gif") || url.endsWith(".jpg") || url.endsWith(".png")
|| url.endsWith(".bmp") || url.endsWith(".css") || url.endsWith(".js")
|| url.endsWith(".jsx")){
return false;
} else {
return true;
}
}
public int saveToDb(String userId, String hostIp,String sessionId,String url,
String operTime,String desc){
//將報表任務資料儲存到資料庫中
Connection conn = null;
Statement st = null;
try {
//構造sql表示式,將資料插入資料庫
conn = ServiceAccess.getSystemSupportService().getDefaultConnection();
st = conn.createStatement();
String sql = "insert into LOG_OBSERVE_HISTORY(USERID,URL,Detail,SessionID,HostName,StartDate) values('"+
userId + "','" + url + "','" + desc + "','" + sessionId
+ "','" + hostIp + "','" + operTime + "')";
if (ServiceAccess.getSystemSupportService().getConnectionType(conn)==ServiceAccess.getSystemSupportService().JCA_TYPE_ORACLE){
sql = "insert into LOG_OBSERVE_HISTORY(Id,USERID,URL,Detail,SessionID,HostName,StartDate) values(LOG_OBSERVE_SEQ.nextval,'"+
userId + "','" + url + "','" + desc + "','" + sessionId
+ "','" + hostIp + "',TO_DATE('" + operTime
+ "','YYYY-MM-DD HH24:MI:SS'))";
}
st.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
log.error("--------------------The url String is:" + url + "-------------------------------");
return 1; //表示操作失敗
} finally {
if (null != st)
{
try{
st.close();
}
catch(Exception e)
{
e.printStackTrace();
}
st = null;
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
conn = null;
}
}
return 0; //表示操作成功
}
}
<filter>
<filter-name>ObserveFilter</filter-name>
<filter-class>com.qwserv.itm.pfl.log.svr.ObserveFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ObserveFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
五.Filter防止使用者訪問一些未被授權的資源
- package
com.drp.util.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;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- public class AuthFilter implements Filter {
- public void destroy() {
- }
- public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
- FilterChain filterChain) throws IOException, ServletException {//1,doFilter方法的第一個引數為ServletRequest物件。此物件給過濾器提供了對進入的資訊(包括表單資料、cookie和HTTP請求頭)的完全訪問。第二個引數為ServletResponse,通常在簡單的過濾器中忽略此引數。最後一個引數為FilterChain,此引數用來呼叫servlet或JSP頁。
- HttpServletRequest request = (HttpServletRequest)servletRequest;//;//如果處理HTTP請求,並且需要訪問諸如getHeader或getCookies等在ServletRequest中無法得到的方法,就要把此request物件構造成HttpServletRequest
- HttpServletResponse response = (HttpServletResponse)servletResponse。
- String currentURL = request.getRequestURI();//取得根目錄所對應的絕對路徑:
- String targetURL = currentURL.substring(currentURL.indexOf("/", 1), currentURL.length()); //擷取到當前檔名用於比較
- HttpSession session = request.getSession(false);
- if (!"/login.jsp".equals(targetURL)) {//判斷當前頁是否是重定向以後的登入頁面頁面,如果是就不做session的判斷,防止出現死迴圈
- if (session == null || session.getAttribute("user") == null) {//*使用者登入以後需手動新增session
- System.out.println("request.getContextPath()=" + request.getContextPath());
- response.sendRedirect(request.getContextPath() + "/login.jsp");//如果session為空表示使用者沒有登入就重定向到login.jsp頁面
- return;
- }
- }
- //加入filter鏈繼續向下執行
- filterChain.doFilter(request, response);//.呼叫FilterChain物件的doFilter方法。Filter介面的doFilter方法取一個FilterChain物件作為它的一個引數。在呼叫此物件的doFilter方法時,啟用下一個相關的過濾器。如果沒有另一個過濾器與servlet或JSP頁面關聯,則servlet或JSP頁面被啟用。
- }
- public void init(FilterConfig filterConfig) throws ServletException {
- }
- }
<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>com.drp.util.filter.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>*.jsp</url-pattern>//表示對所有jsp檔案有效
</filter-mapping>