溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java中filter用法完整代碼示例

發(fā)布時間:2020-09-24 00:11:13 來源:腳本之家 閱讀:197 作者:胡一生 欄目:編程語言

本文研究的主要是Java中filter過濾器的相關(guān)用法,具體實現(xiàn)代碼如下。

filter過濾器主要使用于前臺向后臺傳遞數(shù)據(jù)是的過濾操作。程度很簡單就不說明了,直接給幾個已經(jīng)寫好的代碼:

一、使瀏覽器不緩存頁面的過濾器

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 用于的使 Browser 不緩存頁面的過濾器
 */
public class ForceNoCacheFilter implements Filter {
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException
  {
    ((HttpServletResponse) response).setHeader("Cache-Control","no-cache");
    ((HttpServletResponse) response).setHeader("Pragma","no-cache");
    ((HttpServletResponse) response).setDateHeader ("Expires", -1);
    filterChain.doFilter(request, response);
  }
  public void destroy()
  {
  }
  public void init(FilterConfig filterConfig) throws ServletException
  {
  }
}

二、檢測用戶是否登陸的過濾器

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;
/** 
 * 用于設(shè)置 HTTP 請求字符編碼的過濾器,通過過濾器參數(shù)encoding指明使用何種字符編碼,用于處理Html Form請求參數(shù)的中文問題 
 */
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進(jìn)行過濾,如果是js/css/image則不進(jìn)行處理
		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);
			}
			//保存到數(shù)據(jù)庫中
			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){
		//將報表任務(wù)數(shù)據(jù)保存到數(shù)據(jù)庫中
		Connection conn = null;
		Statement st = null;
		try {
			//構(gòu)造sql表達(dá)式,將數(shù)據(jù)插入數(shù)據(jù)庫
			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防止用戶訪問一些未被授權(quán)的資源

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方法的第一個參數(shù)為ServletRequest對象。此對象給過濾器提供了對進(jìn)入的信息(包括表單數(shù)據(jù)、cookie和HTTP請求頭)的完全訪問。第二個參數(shù)為ServletResponse,通常在簡單的過濾器中忽略此參數(shù)。最后一個參數(shù)為FilterChain,此參數(shù)用來調(diào)用servlet或JSP頁。  
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		//;//如果處理HTTP請求,并且需要訪問諸如getHeader或getCookies等在ServletRequest中無法得到的方法,就要把此request對象構(gòu)造成HttpServletRequest  
		HttpServletResponse response = (HttpServletResponse)servletResponse。  
		        String currentURL = request.getRequestURI();
		//取得根目錄所對應(yīng)的絕對路徑:  
		String targetURL = currentURL.substring(currentURL.indexOf("/", 1), currentURL.length());
		//截取到當(dāng)前文件名用于比較  
		HttpSession session = request.getSession(false);
		if (!"/login.jsp".equals(targetURL)) {
			//判斷當(dāng)前頁是否是重定向以后的登錄頁面頁面,如果是就不做session的判斷,防止出現(xiàn)死循環(huán)  
			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鏈繼續(xù)向下執(zhí)行  
		filterChain.doFilter(request, response);
		//.調(diào)用FilterChain對象的doFilter方法。Filter接口的doFilter方法取一個FilterChain對象作為它的一個參數(shù)。在調(diào)用此對象的doFilter方法時,激活下一個相關(guān)的過濾器。如果沒有另一個過濾器與servlet或JSP頁面關(guān)聯(lián),則servlet或JSP頁面被激活。
	}
	public void init(FilterConfig filterConfig) throws ServletException {
	}
}

html

<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>

總結(jié)

以上就是本文關(guān)于Java中filter用法完整代碼示例的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI