您好,登錄后才能下訂單哦!
本文研究的主要是Java中filter過濾器的相關用法,具體實現代碼如下。
filter過濾器主要使用于前臺向后臺傳遞數據是的過濾操作。程度很簡單就不說明了,直接給幾個已經寫好的代碼:
一、使瀏覽器不緩存頁面的過濾器
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; /** * 用于設置 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 { } }
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>
總結
以上就是本文關于Java中filter用法完整代碼示例的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。