大家好,又见面了,我是你们的朋友全栈君。
使用YUICompressor自动压缩JavaWeb项目中的JS与CSS文件
### 引入Maven依赖
“`html
com.yahoo.platform.yui
yuicompressor
2.4.8
“`
Java 代码
“`java
package com.itshidu.jeelite.common.web;
import com.itshidu.jeelite.common.util.CompressorUtil;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
/**
* 自动压缩JS与CSS
* 当访问指定的目录时,会自动压缩并重定向,我们正常开发访问即可
*/
@WebFilter(urlPatterns={“/res/*”})
public class YUICompressorFilter implements Filter{
//URL对应的文件最后修改时间是什么
private static ConcurrentHashMap LastModify = new ConcurrentHashMap();
/* —- Filter —- */
@Override
public void destroy() { }
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
ServletContext application = request.getServletContext();
//String basepath=request.getScheme() ”://” request.getServerName() ”:” request.getServerPort() request.getContextPath() ”/”;
String distpath = “/WEB-INF/yuimin”;
String distDirAbs = application.getRealPath(distpath); //发布的真实文件路径
String path = request.getServletPath(); //访问的URL:/res/xx/xxxx.js
String srcabs = application.getRealPath(path);
File srcfile = new File(srcabs); //访问的源文件
File distfile = new File(distDirAbs,path); //最终发布在项目中的压缩文件
if(!path.endsWith(“.js”)&&!path.endsWith(“.css”)){
chain.doFilter(request,response);return;
}
if(!distfile.getParentFile().exists()){
distfile.getParentFile().mkdirs();
}
if(!srcfile.exists()){ //源文件不存在
chain.doFilter(request,response);return;
}
if(LastModify.get(path)==null#124;#124;srcfile.lastModified()!=LastModify.get(path)){ //如果源文件被修改
CompressorUtil.compress(srcfile,distfile);
LastModify.put(path,srcfile.lastModified());
System.out.println(“压缩:” path);
}
request.getRequestDispatcher(distpath path).forward(request,response);
}
@Override
public void init(FilterConfig arg0) throws ServletException { }
}
“`
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/161216.html原文链接:https://javaforall.cn