java中filter的用法

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

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

Java代碼 復制代碼
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
?{
?}
}
二、檢測用戶是否登陸的過濾器
?
  1. import?javax.servlet.*; ??
  2. 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()); ??
  • ???} ??
  • ??} ??
  • ?} ??
  • }??

三、字符編碼的過濾器

  1. import?javax.servlet.*; ??
  2. import?java.io.IOException; ??
  3. ??
  4. /** ?
  5. ?*?用于設置?HTTP?請求字符編碼的過濾器,通過過濾器參數encoding指明使用何種字符編碼,用于處理Html?Form請求參數的中文問題 ?
  6. ?*/??
  7. public?class?CharacterEncodingFilter ??
  8. ?implements?Filter ??
  9. { ??
  10. ?protected?FilterConfig?filterConfig?=?null; ??
  11. ?protected?String?encoding?=?""; ??
  12. ??
  13. ?public?void?doFilter(ServletRequest?servletRequest,?ServletResponse?servletResponse,?FilterChain?filterChain)?throws?IOException,?ServletException ??
  14. ?{ ??
  15. ????????if(encoding?!=?null) ??
  16. ?????????servletRequest.setCharacterEncoding(encoding); ??
  17. ????????filterChain.doFilter(servletRequest,?servletResponse); ??
  18. ?} ??
  19. ??
  20. ?public?void?destroy() ??
  21. ?{ ??
  22. ??filterConfig?=?null; ??
  23. ??encoding?=?null; ??
  24. ?} ??
  25. ??
  26. ?public?void?init(FilterConfig?filterConfig)?throws?ServletException ??
  27. ?{ ??
  28. ????????this.filterConfig?=?filterConfig; ??
  29. ????????this.encoding?=?filterConfig.getInitParameter("encoding"); ??
  30. ??
  31. ?} ??
  32. }??

四、記錄用戶的訪問操作器

代碼:
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防止用戶訪問一些未被授權的資源

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

轉載于:https://www.cnblogs.com/yqskj/articles/2226774.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/275224.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/275224.shtml
英文地址,請注明出處:http://en.pswp.cn/news/275224.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

我很喜歡玩游戲,那么我就適合做游戲程序員嗎?

作者&#xff1a;黃小斜文章來源&#xff1a;【程序員江湖】游戲在今天的普及度已經不是端游時代可以比肩的了。如今人手一臺手機、平板就可以吃雞、打農藥&#xff0c;不僅是男生&#xff0c;也有很多女生加入了游戲圈。相信現在在看文章的你也玩游戲&#xff0c;雖然愛玩的程…

open-falcon_NASA在Falcon 9上帶回了蠕蟲-其背后的故事是什么?

open-falconYes, that’s right. The classic NASA “worm” logo is back! An image of the revived NASA worm logo was released on Twitter by NASA Administrator Jim Bridenstine as well as press release on the NASA.gov website. NASA explained that original NASA …

聽說你對 ES6 class 類還不是很了解

大家好&#xff0c;我是若川。最近組織了源碼共讀活動&#xff0c;感興趣的可以加我微信 ruochuan12 參與。前言在ES5中是原型函數&#xff0c;到了ES6中出現了"類"的概念。等同于是ES5的語法糖&#xff0c;大大提升了編寫代碼的速度&#xff0c;本文只講一些常用的&…

《CSS揭秘》讀書筆記

摘要 《CSS揭秘》主要是介紹了使用CSS的技巧&#xff0c;通過47個案例來靈活的使用CSS進行實現&#xff0c;同時在實現過程中注重CSS代碼的靈活性與健壯性。通過閱讀這本書有利于我們編寫高質量的CSS代碼以及打破使用CSS時的固定思維&#xff0c;能夠更加靈活的使用CSS。 《CSS…

一篇文章帶你搞懂前端面試技巧及進階路線

大家好&#xff0c;我是若川。最近有很多朋友給我后臺留言&#xff1a;自己投了不少簡歷&#xff0c;但是收到的面試邀請卻特別少&#xff1b;好不容易收到了大廠的面試邀請&#xff0c;但由于對面試流程不清楚&#xff0c;準備的特別不充分&#xff0c;結果也掛了&#xff1b;…

小屏幕 ui設計_UI設計基礎:屏幕

小屏幕 ui設計重點 (Top highlight)第4部分 (Part 4) Welcome to the fourth part of the UI Design basics. This time we’ll cover the screens you’ll likely design for. This is also a part of the free chapters from Designing User Interfaces.歡迎使用UI設計基礎知…

RabbitMQ指南之四:路由(Routing)和直連交換機(Direct Exchange)

在上一章中&#xff0c;我們構建了一個簡單的日志系統&#xff0c;我們可以把消息廣播給很多的消費者。在本章中我們將增加一個特性&#xff1a;我們可以訂閱這些信息中的一些信息。例如&#xff0c;我們希望只將error級別的錯誤存儲到硬盤中&#xff0c;同時可以將所有級別&am…

不用任何插件實現 WordPress 的彩色標簽云

側邊欄的標簽云&#xff08;Tag Cloud&#xff09;一直是 WordPress 2.3 以后的內置功能&#xff0c;一般直接調用函數wp_tag_cloud 或者在 Widgets 里開啟即可&#xff0c;但是默認的全部是一個顏色&#xff0c;只是大小不一樣&#xff0c;很是不順眼&#xff0c;雖然可以用 S…

隨時隨地能寫代碼, vscode.dev 出手了

大家好&#xff0c;我是若川。最近組織了源碼共讀活動&#xff0c;感興趣的可以加我微信 ruochuan12 參與。今天偶然看到了 VSCode 官方發布了一條激動人心的 Twitter&#xff0c;vscode.dev[1] 域名上線了&#xff01;image-20211021211915942新的域名 vscode.dev[2] 它是一個…

七種主流設計風格_您是哪種設計風格?

七種主流設計風格重點 (Top highlight)I had an idea for another mindblowing test, so here it is. Since you guys liked the first one so much, and I got so many nice, funny responses and private messages on how accurate it actually was, I thought you will prob…

算法精講:分享一道值得分享的算法題

分享一道leetcode上的題&#xff0c;當然&#xff0c;居然不是放在刷題貼里來講&#xff0c;意味著分享的這道題不僅僅是教你怎么來解決&#xff0c;更重要的是這道題引發出來的一些解題技巧或許可以用在其他地方&#xff0c;下面我們來看看這道題的描述。 問題描述 給定一個未…

正幾邊形可以實現無縫拼接?

正n邊形內角為 (n-2)*180/n &#xff0c;要保證可以無縫拼接&#xff0c;就是一個圓可以被整數個n邊形內角拼接&#xff0c;即 360k*(n-2)*180/n > 2nk(n-2)。&#xff08;摘自http://blog.csdn.net/ray58750034/article/details/1365813&#xff09; 以下代碼表明&#xff…

React 18 Beta 來了

大家好&#xff0c;我是若川。最近組織了源碼共讀活動&#xff0c;感興趣的可以加我微信 ruochuan12 參與&#xff0c;目前近3000人參與。經過「React18工作組」幾個月工作&#xff0c;11月16日v18終于從Alpha版本更新到Beta版本。本文會解釋&#xff1a;這次更新帶來的變化對開…

osg著色語言著色_探索數字著色

osg著色語言著色Learn how to colorize icons with your NounPro subscription and Adobe Illustrator.了解如何使用NounPro訂閱和Adobe Illustrator為圖標著色。 For those who want to level up their black and white Noun Project icons with a splash of color, unlockin…

upc組隊賽15 Supreme Number【打表】

Supreme Number題目鏈接 題目描述 A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. Now lets define a number N as the supreme number if and only if each number made up of an non-e…

CSS3實踐之路(一):CSS3之我觀

CSS 的英文全稱Cascading Style Sheets&#xff0c;中文意思是級聯樣式表,通過設立樣式表&#xff0c;可以統一地控制HMTL中各DOM元素的顯示屬性。級聯樣式表可以使人更能有效地控制網頁外觀。使用級聯樣式表&#xff0c;可以擴充精確指定網頁元素位置&#xff0c;外觀以及創建…

18個項目必備的JavaScript代碼片段——數組篇

大家好&#xff0c;我是若川。最近組織了源碼共讀活動&#xff0c;感興趣的可以加我微信 ruochuan12 參與&#xff0c;目前近3000人參與&#xff0c;0-5年工作經驗的都可以參與學習。1.chunk轉換二維數組將數組&#xff08;array&#xff09;拆分成多個數組&#xff0c;并將這些…

美學評價_卡美學的真正美

美學評價In collectible card games like Hearthstone, Legends of Runeterra, and Magic: The Gathering, the aesthetic of the cards is indubitably one of the greatest highlights for many, if not all players. Although the game loop is reliant on physically build…

好程序員web前端分享CSS Bug、CSS Hack和Filter學習筆記

為什么80%的碼農都做不了架構師&#xff1f;>>> CSS Bug、CSS Hack和Filter學習筆記 1)CSS Bug:CSS樣式在各瀏覽器中解析不一致的情況&#xff0c;或者說CSS樣式在瀏覽器中不能正確顯示的問題稱為CSS bug. 2)CSS Hack: CSS中&#xff0c;Hack是指一種兼容CSS在不同…

as3 淺復制 深復制

基元數據類型&#xff1a;boolean、int、uint、number、string 兩種復雜數據類型&#xff1a;array、object 當數組元素全部是基元數據類型時&#xff0c;即全部是值類型時&#xff0c;是沒有淺復制和深復制的區別。 當數組元素全部是復雜數據類型&#xff0c;即引用類型時&…