javaWeb客户端使用缓存过滤器服务器端使用gzip压缩提高访问效率

缓存过滤器:让客户端使用已经加载过的资源,不重复到服务器端请求资源。

package org.per.lm.cachefilter;

import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
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 CacheFilter
  implements Filter
{
  boolean isFil = false;//是否进行过滤
  boolean isPrintMsg = false;//是否在控制台显示过滤消息
  List<String> noFilFolder = null;

  public void init(FilterConfig config) throws ServletException {
    if (config.getInitParameter("isFil").toLowerCase().equals("true"))
      this.isFil = true;
    if (this.isFil) {
      if (config.getInitParameter("noFilFolder") != null) {
        String noFilFolderstr = config.getInitParameter("noFilFolder");
        if (!noFilFolderstr.equals("")) {
          if (noFilFolderstr.indexOf(",") == -1) {
            this.noFilFolder = new ArrayList();
            this.noFilFolder.add(noFilFolderstr);
          } else {
            this.noFilFolder = new ArrayList();
            String[] noFilFolderarr = noFilFolderstr.split(",");
            for (String s : noFilFolderarr) {
              this.noFilFolder.add(s);
            }
          }
        }

      }

      if ((config.getInitParameter("printMsg") != null) && 
        (config.getInitParameter("printMsg").toLowerCase().equals("true")))
        this.isPrintMsg = true;
    }
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException
  {
    boolean isdoFilter = true;
    if (this.isFil) {
      HttpServletRequest httpRequest = (HttpServletRequest)request;
      HttpSession session = httpRequest.getSession();

      List filterFileNameList = new ArrayList();
      if (session.getAttribute("org.per.lm.att.filterFileName") != null)
        filterFileNameList = (List)session.getAttribute("org.per.lm.att.filterFileName");
      else {
        session.setAttribute("org.per.lm.att.filterFileName", filterFileNameList);
      }
      String url = httpRequest.getServletPath();
      url = url.substring(1);
      String hz = url.substring(url.lastIndexOf(".") + 1);
      isPrintMsg("-------------------------------------");
      isPrintMsg("过滤文件集合size:" + filterFileNameList.size());
      isPrintMsg(url);

      if (url.indexOf("/") != -1) {
        boolean flag = false;
        if (this.noFilFolder != null) {
          for (String name : this.noFilFolder) {
            if (url.indexOf(name) == 0) {
              flag = true;
              isPrintMsg(name + "文件夹不过滤!");
              break;
            }
          }
        }
        if (!flag) {
          if (filterFileNameList.contains(url)) {
            isPrintMsg("过滤掉:" + url);
            ((HttpServletResponse)response).setStatus(304);

            isdoFilter = false;
          } else {
            isPrintMsg("新增过滤:" + url);
            filterFileNameList.add(url);
            session.setAttribute("org.per.lm.att.filterFileName", filterFileNameList);
          }

        }

      }
      else if (filterFileNameList.contains(url)) {
        isPrintMsg("过滤掉:" + url);
        ((HttpServletResponse)response).setStatus(304);
        isdoFilter = false;
      } else {
        isPrintMsg("新增过滤:" + url);
        filterFileNameList.add(url);
        session.setAttribute("org.per.lm.att.filterFileName", filterFileNameList);
      }
    }

    if (isdoFilter)
      chain.doFilter(request, response);
  }

  public void destroy()
  {
  }

  private void isPrintMsg(String log)
  {
    if (this.isPrintMsg)
      System.out.println(log);
  }
}
web.xml配置:
<filter>
  <filter-name>cache-filter</filter-name>
  <filter-class>org.per.lm.cachefilter.CacheFilter</filter-class>
  <init-param>    
        <param-name>isFil</param-name>    
        <param-value>true</param-value><!-- 是否开启过滤  true开启  false或其他不开启 -->
  </init-param> 
  <init-param>    
        <param-name>noFilFolder</param-name>    
        <param-value>images,js/myjs</param-value><!-- 不需要过滤的文件夹 多个文件夹以,隔开 不填将全过滤-->
  </init-param>
  <init-param>    
        <param-name>printMsg</param-name>    
        <param-value></param-value><!-- 是否打印过滤信息  true打印  false或其他不打印 -->
  </init-param>   
  <init-param>    
        <param-name>sessionPassedTime</param-name>    
        <param-value>120</param-value><!-- 设置session过期时间(过滤器的有效时间)  单位分钟  格式不对默认为30分钟 不能设置为0 否则会出错 -->
  </init-param> 
  </filter>

<filter-mapping>
  <filter-name>cache-filter</filter-name>
  <url-pattern>*.js</url-pattern><!--要过滤的文件类型-->
  <url-pattern>*.css</url-pattern>
</filter-mapping>

gzip:Gzip开启以后会将输出到用户浏览器的数据进行压缩的处理,这样就会减小通过网络传输的数据量,提高浏览的速度。

package org.per.lm.gzipfilter;

import java.io.IOException;    

import java.util.Enumeration;    

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;    

public class GzipFilter implements Filter {    
 
     private boolean isGzip = true;

     @SuppressWarnings("unchecked")    

     public void doFilter(ServletRequest request, ServletResponse response,    
             FilterChain chain) throws IOException, ServletException { 

         boolean compress = false;    

         if (request instanceof HttpServletRequest){    
             HttpServletRequest httpRequest = (HttpServletRequest) request;    
             Enumeration headers = httpRequest.getHeaders("Accept-Encoding");    
             while (headers.hasMoreElements()){    
                 String value = (String) headers.nextElement();    
                 if (value.indexOf("gzip") != -1)   
                     compress = true;    
             }    
         }    

         if (compress && isGzip){//如果浏览器支持则压缩    
             HttpServletResponse httpResponse = (HttpServletResponse) response;    
             httpResponse.addHeader("Content-Encoding", "gzip");    
             CompressionResponse compressionResponse= new CompressionResponse(httpResponse);    
             chain.doFilter(request, compressionResponse);    
             compressionResponse.close();    
         }else//如果浏览器不支持则不压缩    
             chain.doFilter(request, response);    
             

     }    

     public void init(FilterConfig config) throws ServletException {    

    	 String isGzipstr = config.getInitParameter("isGzip");
    	 if(isGzipstr == null || isGzipstr.equals("") || !isGzipstr.toLowerCase().equals("true"))
    		 isGzip = false;
     }    

     

     public void destroy(){    

     }    

 }    

 




import java.io.IOException; 

import java.io.PrintWriter;    

import javax.servlet.ServletOutputStream;    

import javax.servlet.http.HttpServletResponse;    

import javax.servlet.http.HttpServletResponseWrapper;    

 

public class CompressionResponse extends HttpServletResponseWrapper{

    protected HttpServletResponse response;    

    private ServletOutputStream out;    

    private CompressedStream compressedOut;   

    private PrintWriter writer;    

    protected int contentLength;    

    public CompressionResponse(HttpServletResponse response) throws IOException {    

       super(response); 

       this.response = response;    

       compressedOut = new CompressedStream(response.getOutputStream());  

    }

    public void setContentLength(int len) {  

       contentLength = len;    

    }

    public ServletOutputStream getOutputStream() throws IOException {    

       if (null == out) {    

           if (null != writer) {   

              throw new IllegalStateException("getWriter() has already been called on this response.");    

           }

           out = compressedOut;    

       }

       return out;  

    }

    public PrintWriter getWriter() throws IOException {   

       if (null == writer) {    

           if (null != out) {    

              throw new IllegalStateException("getOutputStream() has already been called on this response."); 

           }

           writer = new PrintWriter(compressedOut);   

       }

       return writer;    

    }

    public void flushBuffer() {    

       try {    

           if (writer != null) { 

              writer.flush();

           }else if (out != null) {   

              out.flush();    

           }

       }catch (IOException e) {   

           e.printStackTrace();    

       }

    }

    public void reset() {

       super.reset();    

       try {    

           compressedOut.reset();    

       }catch (IOException e) {   

           throw new RuntimeException(e);    

       }

    }

    public void resetBuffer() {    

       super.resetBuffer();    

       try {    

           compressedOut.reset();    

       }catch (IOException e) {   

           throw new RuntimeException(e); 

       }

    }

    public void close() throws IOException {    

       compressedOut.close();    

    }

 

}

 




import java.io.IOException;  

import java.util.zip.GZIPOutputStream;  

import javax.servlet.ServletOutputStream;  

public class CompressedStream extends ServletOutputStream {  

       private ServletOutputStream out;  

       private GZIPOutputStream    gzip;  

     /** 

     * 指定压缩缓冲流 

     * @param 输出流到压缩 

     * @throws IOException if an error occurs with the {@link GZIPOutputStream}. 

     */  

       public CompressedStream(ServletOutputStream out) throws IOException {  

           this.out = out;  

           reset();  

       }  

       /** @see ServletOutputStream * */  

       public void close() throws IOException {  

           gzip.close();  

       }  

       /** @see ServletOutputStream * */  

       public void flush() throws IOException {  

          gzip.flush();  

       }  

       /** @see ServletOutputStream * */  

       public void write(byte[] b) throws IOException {  

           write(b, 0, b.length);  

       }  

       /** @see ServletOutputStream * */  

       public void write(byte[] b, int off, int len) throws IOException {  

           gzip.write(b, off, len);  

       }  

       /** @see ServletOutputStream * */  

       public void write(int b) throws IOException {  

           gzip.write(b);  

       }  

     

       public void reset() throws IOException {  

           gzip = new GZIPOutputStream(out);  

       }  

}  

 
web.xml配置:
 <filter>
    <filter-name>gzip</filter-name>
    <filter-class>org.per.lm.gzipfilter.GzipFilter</filter-class><!-- 在服务器端进行gzip压缩 -->
    <init-param>    
        <param-name>isGzip</param-name>    
        <param-value>true</param-value><!-- 是否开启gzip压缩  只有为true开启  false或其他不开启 -->
    </init-param> 
  </filter>

<filter-mapping>
    <filter-name>gzip</filter-name>
    <url-pattern>*.js</url-pattern><!--需要压缩的类型-->    
    <url-pattern>*.css</url-pattern> 
    <url-pattern>*.html</url-pattern>
     <url-pattern>*.htm</url-pattern>  
  </filter-mapping>

经过测试,这两个过滤器可以结合使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值