java压缩去除html空格和换行解决微信域名下不兼容

简介:

直接贴代码。 java压缩去除html空格和换行解决微信域名下不兼容

调用:content = HtmlCompressor.compress(content);



import java.io.StringReader;
import java.io.StringWriter;
import java.util.*;
import java.util.regex.*;

/*******************************************
 * 压缩jsp,html中的代码,去掉所有空白符、换行符
 * @version 1
 * @author yijianfeng

 * @date     2016-10-24
 *******************************************/
public class HtmlCompressor {
    private static String tempPreBlock = "%%%HTMLCOMPRESS~PRE&&&";
    private static String tempTextAreaBlock = "%%%HTMLCOMPRESS~TEXTAREA&&&";
    private static String tempScriptBlock = "%%%HTMLCOMPRESS~SCRIPT&&&";
    private static String tempStyleBlock = "%%%HTMLCOMPRESS~STYLE&&&";
    private static String tempJspBlock = "%%%HTMLCOMPRESS~JSP&&&";
    
    private static Pattern commentPattern = Pattern.compile("<!--\\s*[^\\[].*?-->", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    private static Pattern itsPattern = Pattern.compile(">\\s+?<", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    private static Pattern prePattern = Pattern.compile("<pre[^>]*?>.*?</pre>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); 
    private static Pattern taPattern = Pattern.compile("<textarea[^>]*?>.*?</textarea>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    private static Pattern jspPattern = Pattern.compile("<%([^-@][\\w\\W]*?)%>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    // <script></script>
    private static Pattern scriptPattern = Pattern.compile("(?:<script\\s*>|<script type=['\"]text/javascript['\"]\\s*>)(.*?)</script>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
    private static Pattern stylePattern = Pattern.compile("<style[^>()]*?>(.+)</style>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    // 单行注释,
    private static Pattern signleCommentPattern = Pattern.compile("//.*");
    // 字符串匹配
    private static Pattern stringPattern = Pattern.compile("(\"[^\"\\n]*?\"|'[^'\\n]*?')");
    // trim去空格和换行符
    private static Pattern trimPattern = Pattern.compile("\\n\\s*",Pattern.MULTILINE);
    private static Pattern trimPattern2 = Pattern.compile("\\s*\\r",Pattern.MULTILINE);
    // 多行注释
    private static Pattern multiCommentPattern = Pattern.compile("/\\*.*?\\*/", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

    private static String tempSingleCommentBlock = "%%%HTMLCOMPRESS~SINGLECOMMENT&&&";  // //占位符
    private static String tempMulitCommentBlock1 = "%%%HTMLCOMPRESS~MULITCOMMENT1&&&";  // /*占位符
    private static String tempMulitCommentBlock2 = "%%%HTMLCOMPRESS~MULITCOMMENT2&&&";  // */占位符
    
    
    public static String compress(String html) throws Exception {
        if(html == null || html.length() == 0) {
            return html;
        }
        
        List<String> preBlocks = new ArrayList<String>();
        List<String> taBlocks = new ArrayList<String>();
        List<String> scriptBlocks = new ArrayList<String>();
        List<String> styleBlocks = new ArrayList<String>();
        List<String> jspBlocks = new ArrayList<String>();
        
        String result = html;
        
        //preserve inline java code
        Matcher jspMatcher = jspPattern.matcher(result);
        while(jspMatcher.find()) {
            jspBlocks.add(jspMatcher.group(0));
        }
        result = jspMatcher.replaceAll(tempJspBlock);
        
        //preserve PRE tags
        Matcher preMatcher = prePattern.matcher(result);
        while(preMatcher.find()) {
            preBlocks.add(preMatcher.group(0));
        }
        result = preMatcher.replaceAll(tempPreBlock);
        
        //preserve TEXTAREA tags
        Matcher taMatcher = taPattern.matcher(result);
        while(taMatcher.find()) {
            taBlocks.add(taMatcher.group(0));
        }
        result = taMatcher.replaceAll(tempTextAreaBlock);
        
        //preserve SCRIPT tags
        Matcher scriptMatcher = scriptPattern.matcher(result);
        while(scriptMatcher.find()) {
            scriptBlocks.add(scriptMatcher.group(0));
        }
        result = scriptMatcher.replaceAll(tempScriptBlock);
        
        // don't process inline css 
        Matcher styleMatcher = stylePattern.matcher(result);
        while(styleMatcher.find()) {
            styleBlocks.add(styleMatcher.group(0));
        }
        result = styleMatcher.replaceAll(tempStyleBlock);
        
        //process pure html
        result = processHtml(result);
        
        //process preserved blocks
        result = processPreBlocks(result, preBlocks);
        result = processTextareaBlocks(result, taBlocks);
        result = processScriptBlocks(result, scriptBlocks);
        result = processStyleBlocks(result, styleBlocks);
        result = processJspBlocks(result, jspBlocks);
        
        preBlocks = taBlocks = scriptBlocks = styleBlocks = jspBlocks = null;
        
        return result.trim();
    }
    
    private static String processHtml(String html) {
        String result = html;
        
        //remove comments
//        if(removeComments) {
            result = commentPattern.matcher(result).replaceAll("");
//        }
        
        //remove inter-tag spaces
//        if(removeIntertagSpaces) {
            result = itsPattern.matcher(result).replaceAll("><");
//        }
        
        //remove multi whitespace characters
//        if(removeMultiSpaces) {
            result = result.replaceAll("\\s{2,}"," ");
//        }
                
        return result;
    }
    
    private static String processJspBlocks(String html, List<String> blocks){
        String result = html;
        for(int i = 0; i < blocks.size(); i++) {
            blocks.set(i, compressJsp(blocks.get(i)));
        }
        //put preserved blocks back
        while(result.contains(tempJspBlock)) {
            result = result.replaceFirst(tempJspBlock, Matcher.quoteReplacement(blocks.remove(0)));
        }
        
        return result;
    }
    private static String processPreBlocks(String html, List<String> blocks) throws Exception {
        String result = html;
        
        //put preserved blocks back
        while(result.contains(tempPreBlock)) {
            result = result.replaceFirst(tempPreBlock, Matcher.quoteReplacement(blocks.remove(0)));
        }
        
        return result;
    }
    
    private static String processTextareaBlocks(String html, List<String> blocks) throws Exception {
        String result = html;
        
        //put preserved blocks back
        while(result.contains(tempTextAreaBlock)) {
            result = result.replaceFirst(tempTextAreaBlock, Matcher.quoteReplacement(blocks.remove(0)));
        }
        
        return result;
    }
    
    private static String processScriptBlocks(String html, List<String> blocks) throws Exception {
        String result = html;
        
//        if(compressJavaScript) {
            for(int i = 0; i < blocks.size(); i++) {
                blocks.set(i, compressJavaScript(blocks.get(i)));
            }
//        }
        
        //put preserved blocks back
        while(result.contains(tempScriptBlock)) {
            result = result.replaceFirst(tempScriptBlock, Matcher.quoteReplacement(blocks.remove(0)));
        }
        
        return result;
    }
    
    private static String processStyleBlocks(String html, List<String> blocks) throws Exception {
        String result = html;
        
//        if(compressCss) {
            for(int i = 0; i < blocks.size(); i++) {
                blocks.set(i, compressCssStyles(blocks.get(i)));
            }
//        }
        
        //put preserved blocks back
        while(result.contains(tempStyleBlock)) {
            result = result.replaceFirst(tempStyleBlock, Matcher.quoteReplacement(blocks.remove(0)));
        }
        
        return result;
    }
    
    private static String compressJsp(String source)  {
        //check if block is not empty
        Matcher jspMatcher = jspPattern.matcher(source);
        if(jspMatcher.find()) {
            String result = compressJspJs(jspMatcher.group(1));
            return (new StringBuilder(source.substring(0, jspMatcher.start(1))).append(result).append(source.substring(jspMatcher.end(1)))).toString();
        } else {
            return source;
        }
    }    
    private static String compressJavaScript(String source)  {
        //check if block is not empty
        Matcher scriptMatcher = scriptPattern.matcher(source);
        if(scriptMatcher.find()) {
            String result = compressJspJs(scriptMatcher.group(1));
            return (new StringBuilder(source.substring(0, scriptMatcher.start(1))).append(result).append(source.substring(scriptMatcher.end(1)))).toString();
        } else {
            return source;
        }
    }
        
    private static String compressCssStyles(String source)  {
        //check if block is not empty
        Matcher styleMatcher = stylePattern.matcher(source);
        if(styleMatcher.find()) {
            // 去掉注释,换行
            String result= multiCommentPattern.matcher(styleMatcher.group(1)).replaceAll("");
            result = trimPattern.matcher(result).replaceAll("");
            result = trimPattern2.matcher(result).replaceAll("");
            return (new StringBuilder(source.substring(0, styleMatcher.start(1))).append(result).append(source.substring(styleMatcher.end(1)))).toString();
        } else {
            return source;
        }
    }
    
    private static String compressJspJs(String source){
        String result = source;
        // 因注释符合有可能出现在字符串中,所以要先把字符串中的特殊符好去掉
        Matcher stringMatcher = stringPattern.matcher(result);
        while(stringMatcher.find()){
            String tmpStr = stringMatcher.group(0);
            
            if(tmpStr.indexOf("//") != -1 || tmpStr.indexOf("/*") != -1 || tmpStr.indexOf("*/") != -1){
                String blockStr = tmpStr.replaceAll("//", tempSingleCommentBlock).replaceAll("/\\*", tempMulitCommentBlock1)
                                .replaceAll("\\*/", tempMulitCommentBlock2);
                result = result.replace(tmpStr, blockStr);
            }
        }
        // 去掉注释
        result = signleCommentPattern.matcher(result).replaceAll("");
        result = multiCommentPattern.matcher(result).replaceAll("");
        result = trimPattern2.matcher(result).replaceAll("");
        result = trimPattern.matcher(result).replaceAll(" ");
        // 恢复替换掉的字符串
        result = result.replaceAll(tempSingleCommentBlock, "//").replaceAll(tempMulitCommentBlock1, "/*")
                .replaceAll(tempMulitCommentBlock2, "*/");
        
        return result;
    }
}



      本文转自yjflinchong 51CTO博客,原文链接:http://blog.51cto.com/yjflinchong/1865083,如需转载请自行联系原作者



相关文章
|
2月前
|
存储 小程序 Java
热门小程序源码合集:微信抖音小程序源码支持PHP/Java/uni-app完整项目实践指南
小程序已成为企业获客与开发者创业的重要载体。本文详解PHP、Java、uni-app三大技术栈在电商、工具、服务类小程序中的源码应用,提供从开发到部署的全流程指南,并分享选型避坑与商业化落地策略,助力开发者高效构建稳定可扩展项目。
|
4月前
|
Java 计算机视觉
微信虚拟视频聊天插件,QQ抖音快手虚拟摄像头工具,替换相机视频流java
实现包含了虚拟摄像头核心功能,可以捕获真实摄像头视频流,处理后输出到虚拟摄像头设备。
|
5月前
|
数据可视化 机器人 Java
聊天软件自动回复脚本,微信抖音快手小红书,消息自动回复工具机器人【java】
包含4个完整模块:主逻辑模块实现核心回复功能,工具模块封装常用函数,UI模块提供可视化控制界面
|
9月前
|
存储 小程序 前端开发
微信小程序与Java后端实现微信授权登录功能
微信小程序极大地简化了登录注册流程。对于用户而言,仅仅需要点击授权按钮,便能够完成登录操作,无需经历繁琐的注册步骤以及输入账号密码等一系列复杂操作,这种便捷的登录方式极大地提升了用户的使用体验
2895 12
|
小程序 前端开发 算法
|
Java API 开发者
Java如何实现企业微信审批流程
大家好,我是V哥。本文分享如何在企业微信中实现审批流程,通过调用企业微信的开放API完成。主要内容包括获取Access Token、创建审批模板、发起审批流程和查询审批结果。提供了一个Java示例代码,帮助开发者快速上手。希望对你有帮助,关注V哥爱编程,编码路上同行。
666 4
|
算法 小程序 Java
java制作海报三:获取微信二维码详情,并改变大小,合成到海报(另一张图片)上
这篇文章介绍了如何使用Java获取微信小程序的二维码,并将其调整大小后合成到海报(另一张图片)上。
247 0
|
小程序
java--微信小程序发送模板消息
java--微信小程序发送模板消息
534 0
|
安全 Java Android开发
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
504 5
|
安全 Java Android开发
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
JavaWeb解压缩漏洞之ZipSlip与Zip炸弹
421 2