java基礎篇---Servlet過濾器


Servlet過濾器從字面上的字意理解為景觀一層次的過濾處理才達到使用的要求,而其實Servlet過濾器就是服務器與客戶端請求與響應的中間層組件,在實際項目開發中Servlet過濾器主要用於對瀏覽器的請求進行過濾處理,將過濾后的請求再轉給下一個資源。

過濾器的基本概念

Filter是在Servlet 2.3之后增加的新功能,當需要限制用戶訪問某些資源或者在處理請求時提前處理某些資源的時候,就可以使用過濾器完成。
過濾器是以一種組件的形式綁定到WEB應用程序當中的,與其他的WEB應用程序組件不同的是,過濾器是采用了“鏈”的方式進行處理的。
 
 
實現過濾器 
在Servlet中,如果要定義一個過濾器,則直接讓一個類實現javax.servlet.Filter接口即可,此接口定義了三個操作方法:
  • public void init(FilterConfig filterConfig) throws ServletException
  • public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException
  • public void destroy()
FilterChain接口的主要作用是將用戶的請求向下傳遞給其他的過濾器或者是Servlet:
  • public void doFilter(ServletRequest request,ServletResponse response) throws IOException,ServletException
在FilterChain接口中依然定義了一個同樣的doFilter()方法,這是因為在一個過濾器后面可能存在着另外一個過濾器,也可能是請求的最終目標(Servlet),這樣就通過FilterChain形成了一個“過濾鏈”的操作,所謂的過濾鏈就類似於生活中玩的擊鼓傳花游戲 
定義一個簡單的過濾器 —— SimpleFilter.java
package com.oumyye.過濾器;
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;
public class SimpleFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {    // 初始化過濾器
        String initParam = config.getInitParameter("ref");     // 取得初始化參數
        System.out.println("** 過濾器初始化,初始化參數 = " + initParam);
    }
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {    // 執行過濾
        System.out.println("** 執行doFilter()方法之前。");
        chain.doFilter(request, response);         // 將請求繼續傳遞
        System.out.println("** 執行doFilter()方法之后。");
    }
    public void destroy() {                // 銷毀過濾
        System.out.println("** 過濾器銷毀。");
    }
}

配置web.xml

<filter>
        <filter-name>simple</filter-name>
        <filter-class>com.oumyye.過濾器.SimpleFilter</filter-class>
<init-param>
<param-name>ref</param-name>
<param-value>HELLOMLDN</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>simple</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

過濾器的應用  —— 編碼過濾 

在進行WEB開發中,編碼過濾是必不可少的操作,如果按照之前的做法,在每一個JSP或者是Servlet中都重復編寫“request.setCharacterEncoding("UTF-8")”的語句肯定是不可取的,會造成大量的代碼重復,那么此時就可以通過過濾器完成這種編碼過濾。 
package com.oumyye.過濾器;
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;
public class EncodingFilter implements Filter {
    private String charSet;             // 設置字符編碼
    public void init(FilterConfig config) throws ServletException {
        this.charSet = config.getInitParameter("charset"); // 取得初始化參數
    }
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding(this.charSet);     // 設置統一編碼
    }
    public void destroy() {
  
} }

配置web.xml文件 

    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>com.oumyye.過濾器.EncodingFilter</filter-class>
        <init-param>
            <param-name>charset</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

過濾器的應用---登陸驗證 

登陸驗證是所有WEB開發中不可缺少的部分,最早的做法是通過驗證session的方式完成,但是如果每個頁面都這樣做的話,則肯定會造成大量的代碼重復,而通過過濾器的方式就可以避免這種重復的操作。
在這里需要注意的是,session本身是屬於HTTP協議的范疇,但是doFilter()方法中定義的是ServletRequest類型的對象,那么要想取得session,則必須進行向下轉型,將ServletRequest變為HttpServletRequest接口對象,才能夠通過getSession()方法取得session對象。 
package com.oumyye.過濾器;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class FilterLogin extends HttpServlet implements Filter {
    private FilterConfig filterConfig;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain filterChain) throws ServletException,
            IOException {
       HttpSession session=((HttpServletRequest)request).getSession();
       response.setCharacterEncoding("gb2312");    //響應客戶端類型
       if(session.getAttribute("user")==null){        //判斷session中是否有user這個對象
       PrintWriter out=response.getWriter();        //創建一個輸出流
           //如果為空則通過javaScript腳本出輸出提示並跳轉到index.jsp頁面
       out.print("<script language=javascript>alert('您還沒有登錄!!!');window.location.href='../index.jsp';</script>");
       }else{
          filterChain.doFilter(request, response);//否則繼續執行
       }
    }
    public void destroy() {
    }
}

User.java

package com.mr.filter;

public class User {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

配置web.XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
<filter>
    <filter-name>filterUser</filter-name>
    <filter-class>com.oumyye.過濾器.FilterLogin</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>filterUser</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

jsp頁面:

index.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link href="css/style.css" rel="stylesheet" type="text/css" >
<script language="javascript" type="">
function checkEmpty(){
if(document.form.name.value==""){
alert("用戶名不能為空")
document.form.name.focus();
return false;
}
if(document.form.password.value==""){
alert("密碼不能為空")
document.form.password.focus();
return false;
}
}
</script>

<title>使用過濾器身份驗證</title>
</head>

<body>    
    <h3>&nbsp;</h3>
    <p align="center">使用過濾器身份驗證</p>
    <form name="form" method="post" action="loginresult.jsp" onSubmit="return checkEmpty()">
<table width="220"  border="1" align="center" cellpadding="0" cellspacing="0" bgcolor="808080">
    
  <tr>
    <td align="center">用戶名:</td>
    <td ><input name="name" type="text"></td>
  </tr>
  <tr>
    <td align="center">密&nbsp;&nbsp;碼:</td>
    <td><input name="password" type="password"></td>
  </tr>
  <tr>
      <td align="center" colspan="2">          
          <input type="submit" name="Submit" value="登錄">
          <input type="submit" value="退出"/>
      </td>
  </tr>
</table><br>
</form>

</body>
</html>

loginresult.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" %>
<%@ page import="com.mr.filter.User"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>使用過濾器身份驗證</title>
</head>
<%
request.setCharacterEncoding("gb2312");
String name=request.getParameter("name");
String password=request.getParameter("password");
  User user=new User();
  user.setUsername(name);
  user.setPassword(password);
  session.setAttribute("user",user);

response.sendRedirect("filter/loginsuccee.jsp");
%>
<body>
</body>
</html>

loginsuccee.jsp

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<%@ page import="com.mr.filter.User"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>使用過濾器身份驗證</title>
</head>
<body><div align="center">

<table width="333" height="285" cellpadding="0" cellspacing="0">
  <tr>
    <td align="center">
      <p>您己成功登錄</p>
      <p><br>
          <a href="backtrack.jsp">返回</a>
        </p></td>
  </tr>
</table>
</div>

</body>
</html>

backtrack.jsp

<%
session.invalidate();
out.print("<script language='javascript'>window.location.href='../index.jsp';</script>");
%>

 小結:

過濾器屬於自動執行的一種Servlet;
過濾器依然需要在web.xml文件中進行配置;
過濾器的常見功能是可以完成編碼過濾及登陸驗證


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM