1. 程式人生 > >javaweb學習總結(十六)——Filter(過濾器)常見應用

javaweb學習總結(十六)——Filter(過濾器)常見應用

一、統一全站字元編碼

  通過配置引數charset指明使用何種字元編碼,以處理Html Form請求引數的中文問題

package me.gacl.web.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.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

/**
* @ClassName: CharacterEncodingFilter
* @Description: 此過濾器用來解決全站中文亂碼問題
* @author: 孤傲蒼狼
* @date: 2014-8-31 下午11:09:37
*
*/ 
public class CharacterEncodingFilter implements Filter {

    private FilterConfig filterConfig = null;
    //設定預設的字元編碼
    private String defaultCharset = "UTF-8";

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String charset = filterConfig.getInitParameter("charset");
        if(charset==null){
            charset = defaultCharset;
        }
        request.setCharacterEncoding(charset);
        response.setCharacterEncoding(charset);
        response.setContentType("text/html;charset="+charset);
        
        MyCharacterEncodingRequest requestWrapper = new MyCharacterEncodingRequest(request);
        chain.doFilter(requestWrapper, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        //得到過濾器的初始化配置資訊
        this.filterConfig = filterConfig;
    }
    
    public void destroy() {

    }
}

/*
1.實現與被增強物件相同的介面 
2、定義一個變數記住被增強物件
3、定義一個構造器,接收被增強物件
4、覆蓋需要增強的方法
5、對於不想增強的方法,直接呼叫被增強物件(目標物件)的方法
 */
 
class MyCharacterEncodingRequest extends HttpServletRequestWrapper{
    
    private HttpServletRequest request;
    public MyCharacterEncodingRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
    }
    /* 重寫getParameter方法
     * @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String)
     */
    @Override
    public String getParameter(String name) {
        
        try{
            //獲取引數的值
            String value= this.request.getParameter(name);
            if(value==null){
                return null;
            }
            //如果不是以get方式提交資料的,就直接返回獲取到的值
            if(!this.request.getMethod().equalsIgnoreCase("get")) {
                return value;
            }else{
                //如果是以get方式提交資料的,就對獲取到的值進行轉碼處理
                value = new String(value.getBytes("ISO8859-1"),this.request.getCharacterEncoding());
                return value;
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

  web.xml檔案中的配置如下:

<filter>
      <filter-name>CharacterEncodingFilter</filter-name>
      <filter-class>me.gacl.web.filter.CharacterEncodingFilter</filter-class>
      <init-param>
          <param-name>charset</param-name>
          <param-value>UTF-8</param-value>
      </init-param>
  </filter>
  
  <filter-mapping>
      <filter-name>CharacterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>

二、禁止瀏覽器快取所有動態頁面

  有3 個HTTP 響應頭欄位都可以禁止瀏覽器快取當前頁面,它們在 Servlet 中的示例程式碼如下:

1 response.setDateHeader("Expires",-1);
2 response.setHeader("Cache-Control","no-cache");
3 response.setHeader("Pragma","no-cache");

並不是所有的瀏覽器都能完全支援上面的三個響應頭,因此最好是同時使用上面的三個響應頭。

  • Expires資料頭:值為GMT時間值,為-1指瀏覽器不要快取頁面
  • Cache-Control響應頭有兩個常用值:
  • no-cache指瀏覽器不要快取當前頁面。
  • max-age:xxx指瀏覽器快取頁面xxx秒。
package me.gacl.web.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;

/**
* @ClassName: NoCacheFilter
* @Description: 禁止瀏覽器快取所有動態頁面
* @author: 孤傲蒼狼
* @date: 2014-8-31 下午11:25:40
*
*/ 
public class NoCacheFilter implements Filter {


    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        //把ServletRequest強轉成HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) req;
        //把ServletResponse強轉成HttpServletResponse
        HttpServletResponse response = (HttpServletResponse) resp;
        //禁止瀏覽器快取所有動態頁面
        response.setDateHeader("Expires", -1);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        
        chain.doFilter(request, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException {

    }
    
    public void destroy() {
        
    }
}

  web.xml檔案中的配置如下:

<filter>
      <filter-name>NoCacheFilter</filter-name>
      <filter-class>me.gacl.web.filter.NoCacheFilter</filter-class>
  </filter>
  
  <filter-mapping>
      <filter-name>NoCacheFilter</filter-name>
        <!--只攔截Jsp請求-->
      <servlet-name>*.jsp</servlet-name>
  </filter-mapping>

三、控制瀏覽器快取頁面中的靜態資源

  有些動態頁面中引用了一些圖片或css檔案以修飾頁面效果,這些圖片和css檔案經常是不變化的,所以為減輕伺服器的壓力,可以使用filter控制瀏覽器快取這些檔案,以提升伺服器的效能。

package me.gacl.web.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;

/**
* @ClassName: CacheFilter
* @Description: 控制快取的filter
* @author: 孤傲蒼狼
* @date: 2014-9-1 下午9:39:38
*
*/ 
public class CacheFilter implements Filter {

    private FilterConfig filterConfig;

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
    
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        
        //1.獲取使用者想訪問的資源
        String uri = request.getRequestURI(); 
        
        //2.得到使用者想訪問的資源的字尾名
        String ext = uri.substring(uri.lastIndexOf(".")+1);
        
        //得到資源需要快取的時間
        String time = filterConfig.getInitParameter(ext);
        if(time!=null){
            long t = Long.parseLong(time)*3600*1000;
            //設定快取
            response.setDateHeader("expires", System.currentTimeMillis() + t);
        }
        
        chain.doFilter(request, response);

    }

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }
    
    public void destroy() {
        
    }
}

  web.xml檔案中的配置如下:

<!-- 配置快取過濾器 -->
   <filter>
      <filter-name>CacheFilter</filter-name>
      <filter-class>me.gacl.web.filter.CacheFilter</filter-class>
       <!-- 配置要快取的web資源以及快取時間,以小時為單位 -->
      <init-param>
          <param-name>css</param-name>
          <param-value>4</param-value>
      </init-param>
      <init-param>
          <param-name>jpg</param-name>
          <param-value>1</param-value>
      </init-param>
      <init-param>
          <param-name>js</param-name>
          <param-value>4</param-value>
      </init-param>
      <init-param>
          <param-name>png</param-name>
          <param-value>4</param-value>
      </init-param>
  </filter>
  <!-- 配置要快取的web資源的字尾-->
  <filter-mapping>
      <filter-name>CacheFilter</filter-name>
      <url-pattern>*.jpg</url-pattern>
  </filter-mapping>
  
  <filter-mapping>
      <filter-name>CacheFilter</filter-name>
      <url-pattern>*.css</url-pattern>
  </filter-mapping>
  
  <filter-mapping>
      <filter-name>CacheFilter</filter-name>
      <url-pattern>*.js</url-pattern>
  </filter-mapping>
   <filter-mapping>
      <filter-name>CacheFilter</filter-name>
      <url-pattern>*.png</url-pattern>
  </filter-mapping>

四、實現使用者自動登陸

 思路是這樣的:

  1、在使用者登陸成功後,傳送一個名稱為user的cookie給客戶端,cookie的值為使用者名稱和md5加密後的密碼。   2、編寫一個AutoLoginFilter,這個filter檢查使用者是否帶有名稱為user的cookie來,如果有,則呼叫dao查詢cookie的使用者名稱和密碼是否和資料庫匹配,匹配則向session中存入user物件(即使用者登陸標記),以實現程式完成自動登陸。

  核心程式碼如下:

  處理使用者登入的控制器:LoginServlet

package me.gacl.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.gacl.dao.UserDao;
import me.gacl.domain.User;
import me.gacl.util.WebUtils;

public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        
        UserDao dao = new UserDao();
        User user = dao.find(username, password);
        if(user==null){
            request.setAttribute("message", "使用者名稱或密碼不對!!");
            request.getRequestDispatcher("/message.jsp").forward(request, response);
            return;
        }
        request.getSession().setAttribute("user", user);
        //傳送自動登陸cookie給客戶端瀏覽器進行儲存
        sendAutoLoginCookie(request,response,user);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

    /**
    * @Method: sendAutoLoginCookie
    * @Description: 傳送自動登入cookie給客戶端瀏覽器
    * @Anthor:孤傲蒼狼
    *
    * @param request
    * @param response
    * @param user
    */ 
    private void sendAutoLoginCookie(HttpServletRequest request, HttpServletResponse response, User user) {
        if (request.getParameter("logintime")!=null) {
            int logintime = Integer.parseInt(request.getParameter("logintime"));
            //建立cookie,cookie的名字是autologin,值是使用者登入的使用者名稱和密碼,使用者名稱和密碼之間使用.進行分割,密碼經過md5加密處理
            Cookie cookie = new Cookie("autologin",user.getUsername() + "." + WebUtils.md5(user.getPassword()));
            //設定cookie的有效期
            cookie.setMaxAge(logintime);
            //設定cookie的有效路徑
            cookie.setPath(request.getContextPath());
            //將cookie寫入到客戶端瀏覽器
            response.addCookie(cookie);
        }
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }

}

  處理使用者自動登入的過濾器:AutoLoginFilter

package me.gacl.web.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.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.gacl.dao.UserDao;
import me.gacl.domain.User;
import me.gacl.util.WebUtils;

public class AutoLoginFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //如果已經登入了,就直接chain.doFilter(request, response)放行
        if(request.getSession().getAttribute("user")!=null){
            chain.doFilter(request, response);
            return;
        }
        
        //1.得到使用者帶過來的authlogin的cookie
        String value = null;
        Cookie cookies[] = request.getCookies();
        for(int i=0;cookies!=null && i<cookies.length;i++){
            if(cookies[i].getName().equals("autologin")){
                value = cookies[i].getValue();
            }
        }
        
        //2.得到 cookie中的使用者名稱和密碼 
        if(value!=null){
            String username = value.split("\\.")[0];
            String password = value.split("\\.")[1];
            
            //3.呼叫dao獲取使用者對應的密碼
            UserDao dao = new UserDao();
            User user = dao.find(username);
            String dbpassword = user.getPassword();
            
            //4.檢查使用者帶過來的md5的密碼和資料庫中的密碼是否匹配,如匹配則自動登陸
            if(password.equals(WebUtils.md5(dbpassword))){
                request.getSession().setAttribute("user", user);
            }
        }
        
        chain.doFilter(request, response);
    }
    
    public void destroy() {
        
    }

    public void init(FilterConfig filterConfig) throws ServletException {

    }
}

  如果想取消自動登入,那麼可以在使用者登出時刪除自動登入cookie,核心程式碼如下:

package me.gacl.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CancelAutoLoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //移除儲存在session中的user
        request.getSession().removeAttribute("user");
        //移除自動登入的cookie
        removeAutoLoginCookie(request,response);
        //登出使用者後跳轉到登入頁面
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }

    /**
    * @Method: removeAutoLoginCookie
    * @Description: 刪除自動登入cookie,
    *     JavaWeb中刪除cookie的方式就是新建立一個cookie,新建立的cookie與要刪除的cookie同名,
    *     設定新建立的cookie的cookie的有效期設定為0,有效路徑與要刪除的cookie的有效路徑相同
    * @Anthor:孤傲蒼狼
    *
    * @param request
    * @param response
    */ 
    private void removeAutoLoginCookie(HttpServletRequest request, HttpServletResponse response) {
        //建立一個名字為autologin的cookie
        Cookie cookie = new Cookie("autologin","");
         //將cookie的有效期設定為0,命令瀏覽器刪除該cookie
        cookie.setMaxAge(0);
        //設定要刪除的cookie的path
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}