Java基礎95 過濾器 Filter

一、filter 過濾器的概述        

    filter過濾器:是面向切面編程的一種實現策略,在不影響原來的程序流程的前提下,將一些業務邏輯切入流程中,在請求達到目標以前進行處理,通常用於編碼過濾、權限過濾、....css

二、filter 過濾器的建立步驟  

  一、建立一個普通的java類實現filter接口
  二、實現接口中的三個方法(init,doFilter,destory)
  三、配置過濾器(web.xml)html

三、實例_編碼過濾器            

 1 package com.shore.a_filter;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.Filter;
 6 import javax.servlet.FilterChain;
 7 import javax.servlet.FilterConfig;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 
12 public class CharsetEncoding implements Filter{
13     private String encoding;
14     public void init(FilterConfig config) throws ServletException {//過濾器初始化
15          encoding = config.getInitParameter("encoding");//獲取web.xml配置文件中的參數
16     }
17 
18     public void doFilter(ServletRequest request, ServletResponse response,
19             FilterChain chain) throws IOException, ServletException {
20         request.setCharacterEncoding(encoding);
21         response.setCharacterEncoding(encoding);
22         chain.doFilter(request, response);//放行
23     }
24     
25     public void destroy() {//過濾器被銷燬(服務器中止,纔會被銷燬)
26         
27     }
28 }

web.xml 配置文件java

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7 
 8   <!-- 編碼過濾 -->
 9   <filter>
10       <!-- 類名 -->
11       <filter-name>CharsetEncoding</filter-name>
12       <!-- 類路徑 -->
13       <filter-class>com.shore.a_filter.CharsetEncoding</filter-class>
14       <init-param>
15           <!-- 參數名 -->
16           <param-name>encoding</param-name>
17           <!-- 編碼 -->
18           <param-value>UTF-8</param-value>
19       </init-param>
20   </filter>
21   
22   <filter-mapping>
23       <!-- 類名 -->
24       <filter-name>CharsetEncoding</filter-name>
25       <!--  /* 表示過濾(攔截)全部頁面(請求)     *.xxx 表示攔截該指定後綴結尾的頁面(請求) -->
26       <url-pattern>/*</url-pattern>
27   </filter-mapping>
28 
29 
30   <welcome-file-list>
31     <welcome-file>index.jsp</welcome-file>
32   </welcome-file-list>
33 </web-app>

 

 附錄 

 過濾器web

 1 package com.shore.b_filter;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.Filter;
 6 import javax.servlet.FilterChain;
 7 import javax.servlet.FilterConfig;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 
14 public class LoginFilter implements Filter{
15         private String[] passlist;
16     public void init(FilterConfig Config) throws ServletException {
17         passlist=Config.getInitParameter("passList").split(",");
18         System.out.println("第一步");
19     }
20 
21     public void doFilter(ServletRequest req, ServletResponse resp,
22             FilterChain chain) throws IOException, ServletException {
23         //會重複執行一次
24         System.out.println("第二步");
25         //獲取request對象
26         HttpServletRequest request=(HttpServletRequest)req;
27         HttpServletResponse response=(HttpServletResponse)resp;
28         //獲取客戶端的資源路徑
29         String uri = request.getRequestURI();
30         //獲取請求資源路徑
31         int index = uri.lastIndexOf("/");//獲取路徑中的最後一個斜槓的下標
32         String source = uri.substring(index+1);//截取斜槓後面的全部字符串
33         System.out.println(source);
34         boolean flag = false;//定義標記
35         for(String s:passlist){//遍歷
36             if(s.trim().equals(source)){
37                 flag = true;
38             }
39         }
40         if(flag){//若是flag=true則放行
41             chain.doFilter(request, response);
42         }else{
43             //獲取session的內容
44             Object obj = request.getSession().getAttribute("user");
45             if(obj == null){
46                 //未登陸
47                 request.setAttribute("msg","請先登陸");
48                 request.getRequestDispatcher("index.jsp").forward(request, response);
49             }else{
50                 System.out.println("第五步");
51                 chain.doFilter(request, response);//放行
52             }
53         }
54     }
55 
56     public void destroy() {
57         
58     }
59 }

web.xml 配置文件編程

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app version="2.5" 
 3     xmlns="http://java.sun.com/xml/ns/javaee" 
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 5     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 6     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 7 
 8  <!-- 配置過濾器-->
 9  <filter>
10     <!-- 類名 -->
11      <filter-name>LoginFilter</filter-name>
12     <!-- 類路徑 -->
13      <filter-class>com.shore.b_filter.LoginFilter</filter-class>    
14      <init-param>
15         <!-- 參數名 -->
16          <param-name>passList</param-name>
17         <!-- passList參數的值(放行index和reg頁面,即:不用登錄也可直接訪問這兩個頁面) -->
18          <param-value>index.jsp,reg.jsp</param-value>
19      </init-param>
20  </filter>
21  <filter-mapping>
22     <!-- 類名 -->
23      <filter-name>LoginFilter</filter-name>
24     <!-- 攔截全部jsp頁面 -->
25      <url-pattern>*.jsp</url-pattern>
26  </filter-mapping>
27  
28   <!-- 編碼過濾 -->
29   <filter>
30       <filter-name>CharsetEncoding</filter-name>
31       <filter-class>com.shore.a_filter.CharsetEncoding</filter-class>
32       <init-param>
33           <param-name>encoding</param-name>
34           <param-value>UTF-8</param-value>
35       </init-param>
36   </filter>
37   <filter-mapping>
38       <filter-name>CharsetEncoding</filter-name>
39     <!--  /* 表示過濾(攔截)全部頁面(請求)     *.xxx 表示攔截該指定後綴結尾的頁面(請求) -->
40       <url-pattern>/*</url-pattern>
41   </filter-mapping>
42 
43 
44   <servlet>
45     <description>This is the description of my J2EE component</description>
46     <display-name>This is the display name of my J2EE component</display-name>
47     <servlet-name>LoginServlet</servlet-name>
48     <servlet-class>com.shore.b_servlets.LoginServlet</servlet-class>
49   </servlet>
50   <servlet>
51     <description>This is the description of my J2EE component</description>
52     <display-name>This is the display name of my J2EE component</display-name>
53     <servlet-name>RegisterServlet</servlet-name>
54     <servlet-class>com.shore.b_servlets.RegisterServlet</servlet-class>
55   </servlet>
56   
57   <servlet-mapping>
58     <servlet-name>LoginServlet</servlet-name>
59     <url-pattern>/LoginServlet</url-pattern>
60   </servlet-mapping>
61   <servlet-mapping>
62     <servlet-name>RegisterServlet</servlet-name>
63     <url-pattern>/RegisterServlet</url-pattern>
64   </servlet-mapping>
65   
66   
67   <welcome-file-list>
68     <welcome-file>index.jsp</welcome-file>
69   </welcome-file-list>
70 </web-app>

servlet服務器

 1 package com.shore.b_servlets;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 public class LoginServlet extends HttpServlet {
12 
13     public void doGet(HttpServletRequest request, HttpServletResponse response)
14             throws ServletException, IOException {
15         doPost(request, response);
16     }
17 
18     public void doPost(HttpServletRequest request, HttpServletResponse response)
19             throws ServletException, IOException {
20         String name=request.getParameter("uname");
21         String pass=request.getParameter("upass");
22         System.out.println("第四步");
23         if(!"".equals(name.trim())){
24             //將當前登陸的用戶存儲到session中
25             request.getSession().setAttribute("user",name);
26             //跳轉到主頁
27             response.sendRedirect("main.jsp");
28             
29         }else{
30             request.setAttribute("msg","請輸入帳號和密碼");
31             request.getRequestDispatcher("index.jsp").forward(request, response);
32         }
33     }
34 }

登陸頁面session

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'index.jsp' starting page</title>
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     <meta http-equiv="description" content="This is my page">
18     <!--
19     <link rel="stylesheet" type="text/css" href="styles.css">
20     -->
21   </head>
22   <body>
23           <% 
24               System.out.println("第三步");
25           %>
26           <form action="LoginServlet1" method="post">
27               <input type="text" name="uname"/>
28              <input type="password" name="upass"/>
29              <input type="submit" value="登陸"/>
30              <span>沒有帳號?<a href="reg.jsp">當即註冊</a></span>
31           </form>
32           <hr>
33           <span style="color: red;">${requestScope.msg}</span>
34   </body>
35 </html>

註冊頁面app

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'reg.jsp' starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26     <form action="RegisterServlet">
27         <input type="text" name="uname" placeholder="請輸入帳號"/>
28         <input type="password" name="upass" placeholder="請輸入密碼"/>
29         <input type="password" name="upass" placeholder="請輸入重複密碼"/>
30         <input type="submit" value="註冊"/>
31     </form>
32   </body>
33 </html>

主頁面jsp

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP 'main.jsp' starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26     歡迎來到主頁
27   </body>
28 </html>

 

 

 

 

 

 

原創做者:DSHOREpost

做者主頁:http://www.cnblogs.com/dshore123/

原文出自:http://www.javashuo.com/article/p-oqzpdsbu-hb.html

歡迎轉載,轉載務必說明出處。(若是本文對您有幫助,能夠點擊一下右下角的 推薦,或評論,謝謝!

相關文章
相關標籤/搜索