天涯明月刀ol|天涯明月刀迅雷下载
  1. 當前所在位置:
  2. 首頁
  3. 捕魚大師

Servlet之Filter詳細講解

2018-12-28 admin

 Filter,過濾器,顧名思義,即是對數據等的過濾,預處理過程。為什么要引入過濾器呢?在平常訪問網站的時候,有時候發一些敏感的信息,發出后顯示時 就會將敏感信息用*等字符替代,這就是用過濾器對信息進行了處理。這只是一個簡單的例子,當然,過濾器那么強大,它的功能也不可能局限于此,它不僅能預處 理數據,只要是發送過來的請求它都是可以預處理的,同時,它還可以對服務器返回的響應進行預處理,這樣,大大減輕了服務器的壓力。例如,實現URL級別的 權限訪問控制、過濾敏感詞匯、壓縮響應信息等一些高級功能。下面來詳細介紹一下過濾器。

一、定義

  學習一個東西,我們首先要理解它的定義。

 

 

1.概念

   過濾作用,對從客戶端向服務器端發送的請求進行過濾,也可以對服務器端返回的響應進行處理。它使用戶可以改變一個request和修改一個 response.。Filter 不是一個servlet,它不能產生一個response,但是它能夠在一個request到達servlet之前預處理request,也可以在 response離開servlet時處理response。換句話說,filter其實是客戶端與servlet中間的一個傳遞者,并且它可以對要傳遞 的東西進行修改。

  注意:過濾器是用來攔截請求和響應的,不能產生響應,而servlet是用來處理請求并產生響應的。

 

 

2.適用場合

  實現URL級別的權限訪問控制,過濾敏感詞匯,壓縮響應信息等。

 

 

3.過濾器如何實現攔截

  • 當客戶端發生請求后,在HttpServletRequest 到達Servlet 之前,過濾器攔截客戶的HttpServletRequest 。 
  • 根據需要檢查HttpServletRequest ,也可以修改HttpServletRequest 頭和數據。 
  • 在過濾器中調用doFilter方法,對請求放行。請求到達Servlet后,對請求進行處理并產生HttpServletResponse發送給客戶端。
  • 在HttpServletResponse 到達客戶端之前,過濾器攔截HttpServletResponse 。 
  • 根據需要檢查HttpServletResponse ,可以修改HttpServletResponse 頭和數據。
  • 最后,HttpServletResponse到達客戶端。

 

 

4.Filter接口

  Servlet API提供了一個Filter接口,編寫的過濾器必須實現該接口。

 

 

5.Filter的生命周期

(1)Filter接口中有三個重要的方法。

  • init()方法:初始化參數,在創建Filter時自動調用。當我們需要設置初始化參數的時候,可以寫到該方法中。
  • doFilter()方法:攔截到要執行的請求時,doFilter就會執行。這里面寫我們對請求和響應的預處理。
  • destroy()方法:在銷毀Filter時自動調用。

 

(2)Filter的生命周期

    Filter的創建和銷毀由web服務器控制。

  • 服務器啟動的時候,web服務器創建Filter的實例對象,并調用其init方法,完成對象的初始化功能。filter對象只會創建一次,init方法也只會執行一次。
  • 攔截到請求時,執行doFilter方法。可以執行多次。
  • 服務器關閉時,web服務器銷毀Filter的實例對象。

 

 

6.Filter對象——FilterConfig

  用 戶在配置filter時,可以使用<init-param>為filter配置一些初始化參數,當web容器實例化Filter對象,調用其 init方法時,會把封裝了filter初始化參數的filterConfig對象傳遞進來。因此開發人員在編寫filter時,通過 filterConfig對象的方法,就可獲得:

  • String getFilterName():得到filter的名稱。
  • String getInitParameter(String name): 返回在部署描述中指定名稱的初始化參數的值。如果不存在返回null.
  • Enumeration getInitParameterNames():返回過濾器的所有初始化參數的名字的枚舉集合。
  • public ServletContext getServletContext():返回Servlet上下文對象的引用。

 

 

7.過濾器鏈——FilterChain

  一組過濾器對某些web資源進行攔截,那么這組過濾器就稱為過濾器鏈。過濾器的執行順序和<filter-mapping>有關(誰在前先執行誰)。

二、開發步驟

  了解了過濾器的相關概念,接下來進行實例開發。

 

1.編寫步驟

  • 編寫java類實現Filter接口,并實現其doFilter方法。
  • 在 web.xml 文件中使用<filter>和<filter-mapping>元素對編寫的filter類進行注冊,并設置它所能攔截的資源。

 

2.示例

(1)簡單的Filter示例

  •  編寫FilterDemo1類
復制代碼
 1 package com.oracle.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 FilterDemo1 implements Filter{
13 
14     /*
15      * 對Filter的整個生命周期了解的一個案例
16      * 注意事項:
17      * 1.實現Filter接口時導入的是javax.servlet.Filter包
18      * 2.方法均有web服務器自動調用,不需我們手動調用
19      * 3.init方法中一般寫初始化參數,這里先不用,后面的例子再使用。
20      * 4.destroy方法一般不需要寫任何代碼
21      * 5.重寫doFilter方法,可以寫我們對攔截的請求和響應的處理動作。
22      * 6.寫完該類后配置filter,在web.xml中配置。
23      * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
24      */
25     @Override
26     public void init(FilterConfig filterConfig) throws ServletException {
27         // TODO Auto-generated method stub
28         System.out.println("FilterDemo1的init方法被調用");
29     }
30 
31     @Override
32     public void doFilter(ServletRequest request, ServletResponse response,
33             FilterChain chain) throws IOException, ServletException {
34         // TODO Auto-generated method stub
35         System.out.println("我是FilterDemo1,客戶端向Servlet發送的請求被我攔截到了");
36         chain.doFilter(request, response);
37         System.out.println("我是FilterDemo1,Servlet向客戶端發送的響應被我攔截到了");
38     }
39 
40     @Override
41     public void destroy() {
42         // TODO Auto-generated method stub
43         System.out.println("FilterDemo1的destroy方法被調用");
44     }
45 
46 }
復制代碼
  • 配置filter,在web.xml文件中加入下面這段代碼
復制代碼
1 <filter>
2       <filter-name>filterDemo1</filter-name>
3       <filter-class>com.oracle.filter.FilterDemo1</filter-class>
4   </filter>
5   <filter-mapping>
6       <filter-name>filterDemo1</filter-name>
7       <url-pattern>/*</url-pattern>
8       <!-- /*是對所有的文件進行攔截 -->
9   </filter-mapping>
復制代碼
  • 控制臺結果

  • 分 析:從上面結果可以看出,在服務器啟動時,就調用了init方法,當訪問頁面時,該過濾器攔截到請求執行doFilter方法,在該方法中,使用 doFilter方法,當返回響應后,繼續執行剩下的代碼,執行完成后將響應傳給客戶端。當關閉服務器時,服務器就調用了destroy方法。

 

(2)Filter鏈示例

  • 編寫FilterDemo1類
復制代碼
 1 package com.oracle.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 FilterDemo1 implements Filter{
13 
14     /*
15      * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
16      */
17     @Override
18     public void init(FilterConfig filterConfig) throws ServletException {
19         // TODO Auto-generated method stub
20     }
21 
22     @Override
23     public void doFilter(ServletRequest request, ServletResponse response,
24             FilterChain chain) throws IOException, ServletException {
25         // TODO Auto-generated method stub
26         System.out.println("我是FilterDemo1,客戶端向Servlet發送的請求被我攔截到了");
27         //對請求放行,進入下一個過濾器FilterDemo2
28         chain.doFilter(request, response);
29         System.out.println("我是FilterDemo1,Servlet向客戶端發送的響應被我攔截到了");
30     }
31 
32     @Override
33     public void destroy() {
34         // TODO Auto-generated method stub
35     }
36 
37 }
復制代碼
  •  編寫FilterDemo2類
復制代碼
 1 package com.oracle.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 FilterDemo2 implements Filter{
13 
14     @Override
15     public void init(FilterConfig filterConfig) throws ServletException {
16         // TODO Auto-generated method stub
17         
18     }
19 
20     @Override
21     public void doFilter(ServletRequest request, ServletResponse response,
22             FilterChain chain) throws IOException, ServletException {
23         // TODO Auto-generated method stub
24         System.out.println("我是FilterDemo2,客戶端向Servlet發送的請求被我攔截到了");
25         //對請求放行,進入Servlet
26         chain.doFilter(request, response);
27         System.out.println("我是FilterDemo2,Servlet向客戶端發送的響應被我攔截到了");
28     }
29 
30     @Override
31     public void destroy() {
32         // TODO Auto-generated method stub
33         
34     }
35 
36 }
復制代碼
  •  配置filter,在web.xml文件中加入下面這段代碼
復制代碼
 1 <filter>
 2       <filter-name>filterDemo1</filter-name>
 3       <filter-class>com.oracle.filter.FilterDemo1</filter-class>
 4   </filter>
 5   <filter>
 6       <filter-name>filterDemo2</filter-name>
 7       <filter-class>com.oracle.filter.FilterDemo2</filter-class>
 8   </filter>
 9   
10   <filter-mapping>
11       <filter-name>filterDemo1</filter-name>
12       <url-pattern>/*</url-pattern>
13       <!-- /*是對所有的文件進行攔截 -->
14   </filter-mapping>
15   <filter-mapping>
16       <filter-name>filterDemo2</filter-name>
17       <url-pattern>/*</url-pattern>
18       <!-- /*是對所有的文件進行攔截 -->
19   </filter-mapping>
復制代碼
  •  控制臺結果

  • 分 析:當有多個過濾器對同一個請求進行攔截時,根據web.xml文件中<filter-mapping>的配置順序,誰在前,先執行誰。當第 一過濾器攔截成功后,會執行doFilter方法,該方法中,調用chain.doFilter方法,會將該請求放行給下一個過濾器,依次執行,直到執行 到最后一個過濾器,當最后一個過濾器調用chain.doFilter方法時,請求會被放行給Servlet,當Servlet處理返回響應信息時,先返 回到最后執行的過濾器,繼續執行該過濾器剩下的代碼。依次返回,直到返回到第一個過濾器,最后返回給客戶端。

 

 (3)禁用所有動態頁面的緩存過濾器

  • 編寫FilterDemo3類
復制代碼
 1 package com.oracle.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.HttpServletResponse;
12 
13 public class FilterDemo3 implements Filter{
14 
15     @Override
16     public void init(FilterConfig filterConfig) throws ServletException {
17         // TODO Auto-generated method stub
18         
19     }
20 
21     @Override
22     public void doFilter(ServletRequest request, ServletResponse response,
23             FilterChain chain) throws IOException, ServletException {
24         // 在response的頭部設置Cache-Control、Pragma和Expires即可取消緩存
25         HttpServletResponse resp = (HttpServletResponse)response;
26         resp.setHeader("Cache-Control", "no-cache");
27         resp.setHeader("Pragma", "no-cache");
28         resp.setDateHeader("Expires", -1);
29         chain.doFilter(request, resp);
30     }
31 
32     @Override
33     public void destroy() {
34         // TODO Auto-generated method stub
35         
36     }
37 
38 }
復制代碼
  •  配置filter,在web.xml文件中加入下面這段代碼
復制代碼
1 <filter>
2       <filter-name>filterDemo3</filter-name>
3       <filter-class>com.oracle.filter.FilterDemo3</filter-class>
4   </filter>
5   
6   <filter-mapping>
7       <filter-name>filterDemo3</filter-name>
8       <url-pattern>/*</url-pattern>
9   </filter-mapping>
復制代碼

 

(4) 分IP統計網站的訪問次數過濾器

  • 編寫FilterDemo4類
復制代碼
 1 package com.oracle.filter;
 2 
 3 import java.io.IOException;
 4 import java.util.HashMap;
 5 import java.util.Map;
 6 
 7 import javax.servlet.Filter;
 8 import javax.servlet.FilterChain;
 9 import javax.servlet.FilterConfig;
10 import javax.servlet.ServletContext;
11 import javax.servlet.ServletException;
12 import javax.servlet.ServletRequest;
13 import javax.servlet.ServletResponse;
14 
15 public class FilterDemo4 implements Filter{
16 
17     private FilterConfig filterConfig;
18     @Override
19     public void init(FilterConfig filterConfig) throws ServletException {
20         // TODO Auto-generated method stub
21 
22         //初始化參數,ipCount用來存放ip及訪問次數
23         ServletContext application = filterConfig.getServletContext();
24         Map<String,Integer> ipCount = new HashMap<String,Integer>();
25         application.setAttribute("ipCount",ipCount);
26         this.filterConfig = filterConfig;
27     }
28 
29     
30     @Override
31     public void doFilter(ServletRequest request, ServletResponse response,
32             FilterChain chain) throws IOException, ServletException {
33         // TODO Auto-generated method stub
34         ServletContext application = filterConfig.getServletContext();
35         Map<String,Integer> ipCount = (HashMap<String,Integer>)application.getAttribute("ipCount");
36         String ip = request.getRemoteAddr();
37         Integer count = ipCount.get(ip);
38         if(count != null){
39             //Map中存在該ip
40             count = count + 1;
41         }else{
42             count = 1;
43         }
44         ipCount.put(ip, count);
45         application.setAttribute("ipCount",ipCount);
46         chain.doFilter(request, response);
47     }
48 
49     @Override
50     public void destroy() {
51         // TODO Auto-generated method stub
52 
53     }
54 
55 }
復制代碼
  • 編寫index.jsp頁面
復制代碼
 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12     
13     <title>My JSP 'index.jsp' starting page</title>
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   </head>
23   
24   <body>
25     <h1>分IP統計網站瀏覽次數</h1>
26    <table border="1" width="400">
27        <tr>
28            <th>IP地址</th>
29            <th>瀏覽次數</th>
30        </tr>
31        <c:forEach items="${ipCount}" var="m">
32            <tr>
33                <td>${m.key}</td>
34                <td>${m.value}</td>
35            </tr>
36        </c:forEach>
37    </table>
38   </body>
39 </html>
復制代碼
  • 配置filter,在web.xml文件中加入下面這段代碼
復制代碼
1 <filter>
2       <filter-name>filterDemo4</filter-name>
3       <filter-class>com.oracle.filter.FilterDemo4</filter-class>
4   </filter>
5   
6   <filter-mapping>
7       <filter-name>filterDemo4</filter-name>
8       <url-pattern>/*</url-pattern>
9   </filter-mapping>
復制代碼
  •  網頁結果

 

 

(5)自動登錄

  • 編寫AutoLoginFilter類
復制代碼
 1 package com.oracle.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.Cookie;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpSession;
14 
15 import com.oracle.biz.UserInfoBiz;
16 import com.oracle.biz.impl.UserInfoBizImpl;
17 import com.oracle.entity.UserInfo;
18 import com.oracle.util.CookieUtil;
19 
20 public class AutoLoginFilter implements Filter{
21 
22     @Override
23     public void init(FilterConfig filterConfig) throws ServletException {
24         // TODO Auto-generated method stub
25         
26     }
27 
28     @Override
29     public void doFilter(ServletRequest request, ServletResponse response,
30             FilterChain chain) throws IOException, ServletException {
31         // TODO Auto-generated method stub
32         //先判斷session中是否存在,存在則放行,不存在則判斷cookie中是否存在用戶名密碼,存在則到數據庫中查詢是否正確,正確則存入session并放行,不正確則放行
33         HttpServletRequest req = (HttpServletRequest)request;
34         HttpSession session = req.getSession();
35         UserInfo user = (UserInfo)session.getAttribute("user");
36         if(user != null){
37             chain.doFilter(req, response);
38         }else{
39             //session中不存在用戶
40             Cookie[] cookies = req.getCookies();
41             Cookie cookie = CookieUtil.findCookie(cookies, "autoLogin");
42             if(cookie!=null){
43                 //在cookie中找到該用戶
44                 UserInfoBiz ubiz = new UserInfoBizImpl();
45                 String name = cookie.getValue().split("#oracle#")[0];
46                 String pwd = cookie.getValue().split("#oracle#")[1];
47                 String msg = ubiz.login(name, pwd);
48                 if("登陸成功!".equals(msg)){
49                     user = ubiz.getByName(name);
50                     session.setAttribute("user", user);
51                     chain.doFilter(req, response);
52                 }else{
53                     chain.doFilter(req, response);
54                 }
55             }else{
56                 //沒有找到該客戶
57                 chain.doFilter(req, response);
58             }
59         }
60     }
61 
62     @Override
63     public void destroy() {
64         // TODO Auto-generated method stub
65         
66     }
67 
68     
69 }
復制代碼

 

  • 編寫DoLoginServlet
復制代碼
 1 package com.oracle.servlet;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.http.Cookie;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import javax.servlet.http.HttpSession;
11 
12 import com.oracle.biz.UserInfoBiz;
13 import com.oracle.biz.impl.UserInfoBizImpl;
14 import com.oracle.entity.UserInfo;
15 
16 public class DoLoginServlet extends HttpServlet {
17 
18     /**
19      * Constructor of the object.
20      */
21     public DoLoginServlet() {
22         super();
23     }
24 
25     /**
26      * Destruction of the servlet. <br>
27      */
28     public void destroy() {
29         super.destroy(); // Just puts "destroy" string in log
30         // Put your code here
31     }
32 
33     /**
34      * The doGet method of the servlet. <br>
35      *
36      * This method is called when a form has its tag value method equals to get.
37      * 
38      * @param request the request send by the client to the server
39      * @param response the response send by the server to the client
40      * @throws ServletException if an error occurred
41      * @throws IOException if an error occurred
42      */
43     public void doGet(HttpServletRequest request, HttpServletResponse response)
44             throws ServletException, IOException {
45 
46         doPost(request,response);
47     }
48 
49     /**
50      * The doPost method of the servlet. <br>
51      *
52      * This method is called when a form has its tag value method equals to post.
53      * 
54      * @param request the request send by the client to the server
55      * @param response the response send by the server to the client
56      * @throws ServletException if an error occurred
57      * @throws IOException if an error occurred
58      */
59     public void doPost(HttpServletRequest request, HttpServletResponse response)
60             throws ServletException, IOException {
61 
62         HttpSession session = request.getSession();
63         request.setCharacterEncoding("UTF-8");
64         response.setCharacterEncoding("UTF-8");
65         String name = request.getParameter("myname");
66         String pwd = request.getParameter("pwd");
67         String autoLogin = request.getParameter("autoLogin");
68         UserInfoBiz ubiz = new UserInfoBizImpl();
69         //ubiz.login(name, pwd):判斷用戶是否登陸成功,返回一個字符串。成功則返回"登陸成功!",不成功則返回對應的錯誤提示。
70         String msg = ubiz.login(name, pwd);
71         if("登陸成功!".equals(msg)){
72             UserInfo user = ubiz.getByName(name);
73             session.setAttribute("user", user);
74             if("true".equals(autoLogin)){
75                 //利用cookie記住用戶名和密碼
76                 Cookie cookie = new Cookie("autoLogin",user.getUserName()+"#oracle#"+user.getPassword());
77                 //設置有效時間
78                 cookie.setMaxAge(60*60*24);
79                 //將cookie回寫到瀏覽器
80                 response.addCookie(cookie);
81             }
82             response.sendRedirect("success.jsp");
83         }else{
84             request.setAttribute("msg", msg);
85             request.getRequestDispatcher("login.jsp").forward(request, response);
86         }
87     }
88 
89     /**
90      * Initialization of the servlet. <br>
91      *
92      * @throws ServletException if an error occurs
93      */
94     public void init() throws ServletException {
95         // Put your code here
96     }
97 
98 }
復制代碼
  •  編寫CookieUtil
復制代碼
 1 package com.oracle.util;
 2 
 3 import javax.servlet.http.Cookie;
 4 
 5 
 6 
 7 public class CookieUtil {
 8 
 9     public static Cookie findCookie(Cookie[] cookies,String name){
10         if(cookies==null){
11             return null;
12         }else{
13             for(Cookie cookie:cookies){
14                 if(cookie.getName().equals(name)){
15                     return cookie;
16                 }
17             }
18             return null;
19         }
20     }
21 }
復制代碼
  • 編寫login.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 'login.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="doLogin" method="post">
27         用戶名<input name="myname"><br/>
28         密&nbsp;碼<input type="password" name="pwd"><br/>
29         <input type="checkBox" name="autoLogin" value="true">自動登錄<br/>
30         <input type="submit" value="登陸"> 
31     </form>
32   </body>
33 </html>
復制代碼
  • 編寫success.jsp
復制代碼
 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12     
13     <title>My JSP 'success.jsp' starting page</title>
14     
15     <meta http-equiv="pragma" content="no-cache">
16     <meta http-equiv="cache-control" content="no-cache">
17     <meta http-equiv="expires" content="0">    
18     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
19     <meta http-equiv="description" content="This is my page">
20     <!--
21     <link rel="stylesheet" type="text/css" href="styles.css">
22     -->
23 
24   </head>
25   
26   <body>
27     <c:if test="${empty user}">
28         <h2>您還未登陸,請去<a href="login.jsp">登陸</a></h2>
29     </c:if>
30     <c:if test="${not empty user}">
31         <h2>歡迎你${user.userName}</h2>
32     </c:if>
33   </body>
34 </html>
復制代碼
  • 配置filter和servlet,在web.xml文件中加入下面的代碼
復制代碼
 1 <servlet>
 2     <description>This is the description of my J2EE component</description>
 3     <display-name>This is the display name of my J2EE component</display-name>
 4     <servlet-name>DoLoginServlet</servlet-name>
 5     <servlet-class>com.oracle.servlet.DoLoginServlet</servlet-class>
 6   </servlet>
 7 
 8   <servlet-mapping>
 9     <servlet-name>DoLoginServlet</servlet-name>
10     <url-pattern>/doLogin</url-pattern>
11   </servlet-mapping>    
12   
13   <filter>
14       <filter-name>AutoLoginFilter</filter-name>
15       <filter-class>com.oracle.filter.AutoLoginFilter</filter-class>
16   </filter>
17   <filter-mapping>
18       <filter-name>AutoLoginFilter</filter-name>
19       <url-pattern>/*</url-pattern>
20   </filter-mapping>
復制代碼

 

(6)處理網站的Get和Post請求亂碼

  • 思 路:增強request對象的getParameter方法等方法。編寫一個類MyHttpServletRequest實現 HttpServletRequestWrapper,重寫它的getParameter方法等方法,在這些方法中對不同方式提交的數據進行轉碼。在過濾 器中,將request強制轉換成MyHttpServletRequest類型的對象,這樣,當再次使用getParameter等方法時其實調用的是 你重寫后的getParametr方法,也就是已經處理過的數據,這樣就不用再擔心亂碼的問題了。
  • MyHttpServletRequest類
復制代碼
 1 package com.oracle.bookshop.filter;
 2 
 3 import java.io.UnsupportedEncodingException;
 4 import java.util.Map;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 import javax.servlet.http.HttpServletRequestWrapper;
 8 
 9 
10 public class MyHttpServletRequest extends HttpServletRequestWrapper {
11     /*
12      * 該類重寫
13      */
14     private HttpServletRequest request;
15 
16     private boolean hasEncode;
17 
18     public MyHttpServletRequest(HttpServletRequest request) {
19         super(request);// super必須寫
20         this.request = request;
21     }
22 
23     // 對需要增強方法進行覆蓋
24     @Override
25     public Map getParameterMap() {
26         // 先獲得請求方式
27         String method = request.getMethod();
28         if (method.equalsIgnoreCase("post")) {
29             // post請求
30             try {
31                 // 處理post亂碼
32                 request.setCharacterEncoding("utf-8");
33                 return request.getParameterMap();
34             } catch (UnsupportedEncodingException e) {
35                 e.printStackTrace();
36             }
37         } else if (method.equalsIgnoreCase("get")) {
38             // get請求
39             Map<String, String[]> parameterMap = request.getParameterMap();
40             if (!hasEncode) { // 確保get手動編碼邏輯只運行一次
41                 for (String parameterName : parameterMap.keySet()) {
42                     String[] values = parameterMap.get(parameterName);
43                     if (values != null) {
44                         for (int i = 0; i < values.length; i++) {
45                             try {
46                                 // 處理get亂碼
47                                 values[i] = new String(values[i]
48                                         .getBytes("ISO-8859-1"), "utf-8");
49                             } catch (UnsupportedEncodingException e) {
50                                 e.printStackTrace();
51                             }
52                         }
53                     }
54                 }
55                 hasEncode = true;
56             }
57             return parameterMap;
58         }
59 
60         return super.getParameterMap();
61     }
62 
63     @Override
64     public String getParameter(String name) {
65         Map<String, String[]> parameterMap = getParameterMap();
66         String[] values = parameterMap.get(name);
67         if (values == null) {
68             return null;
69         }
70         return values[0]; // 取回參數的第一個值
71     }
72 
73     @Override
74     public String[] getParameterValues(String name) {
75         Map<String, String[]> parameterMap = getParameterMap();
76         String[] values = parameterMap.get(name);
77         return values;
78     }
79 
80 }
復制代碼
  • 編寫CharacterEnodingFilter
復制代碼
 1 package com.oracle.bookshop.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 
13 public class CharacterEnodingFilter implements Filter{
14 
15     @Override
16     public void destroy() {
17         // TODO Auto-generated method stub
18         
19     }
20 
21     @Override
22     public void doFilter(ServletRequest request, ServletResponse response,
23             FilterChain chain) throws IOException, ServletException {
24         // TODO Auto-generated method stub
25         HttpServletRequest req = (HttpServletRequest)request;
26         MyHttpServletRequest myreq = new MyHttpServletRequest(req);
27         chain.doFilter(myreq, response);
28         
29     }
30 
31     @Override
32     public void init(FilterConfig arg0) throws ServletException {
33         // TODO Auto-generated method stub
34         
35     }
36 
37     
38 }
復制代碼

捕魚駕到 天涯明月刀ol