`
lelong
  • 浏览: 552241 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

压缩js,jsp

 
阅读更多
import com.swift.web.resource.handler.FileEntity;
import com.swift.web.resource.handler.FileScanner;

/*******************************************
 * 压缩jsp,html中的代码,去掉所有空白符、换行符
 * 
 *******************************************/
@SuppressWarnings("nls")
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;
	}

	public static List<FileEntity> compressAll(String rootPath) {

		List entities = new ArrayList();

		//FileScanner.scan(rootPath, new String[] { "jsp", "html" }, new HtmlScanBack(rootPath, entities));
		FileScanner.scan(rootPath, new String[] {"jsp"}, new HtmlScanBack(rootPath, entities));
		return entities;
	}

	static class HtmlScanBack implements FileScanner.ScanCallback {
		private String webRootPath;
		private List<FileEntity> fileEntities;

		public HtmlScanBack(String rootPath, List<FileEntity> entity) {
			this.webRootPath = rootPath;
			if (!this.webRootPath.endsWith(File.separator)) {
				this.webRootPath += File.separator;
			}
			this.fileEntities = entity;
		}

		public void invoke(File file) {
			try {
				
				
			} catch (Exception e) {
			}
		}


		private String getWebPath(String fileName) {
			String webFileName = fileName.substring(this.webRootPath.length());
			return "/" + webFileName.replaceAll("\\\\", "\\/");
		}

	}

}
import com.swift.web.resource.handler.FileEntity;
import com.swift.web.resource.handler.FileScanner;

public class HtmlReplace {
	
	public static void replace(String rootPath, List<FileEntity> entity) {
		//FileScanner.scan(rootPath, new String[] { "jsp", "html", "htm" }, new pageScanBack(entity));
		FileScanner.scan(rootPath, new String[] { "jsp"}, new pageScanBack(entity));
	}

	static class pageScanBack implements FileScanner.ScanCallback {
		private List<FileEntity> fileEntities;

		public pageScanBack(List<FileEntity> entity) {
			this.fileEntities = entity;
		}

		public void invoke(File file) {
			try {
				InputStreamReader inReader = new InputStreamReader(new FileInputStream(file), "UTF-8");
				LineNumberReader inLine = new LineNumberReader(inReader);
				String line = null;
				StringBuffer sb = new StringBuffer();
				while ((line = inLine.readLine()) != null) {
					sb.append(line + "\r\n");
				}
				inReader.close();
				inLine.close();

				String text =HtmlCompressor.compress(sb.toString());
				sb = null;

				/*for (FileEntity fe : this.fileEntities) {
					text = text.replaceAll(fe.fileName + "[^\"']*", fe.getVersionFileName());
				}*/

				OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8");
				writer.write(text);
				writer.flush();
				writer.close();
				inReader = null;
				inLine = null;
				writer = null;
			} catch (Exception e) {
			}
		}
	}
}

 

import com.swift.web.resource.handler.FileEntity;
import com.swift.web.resource.handler.FileScanner;
import com.yahoo.platform.yui.compressor.YUICompressor;

public class JsCssCompressor {
	private static String[] yuiJsArgs;
	private static String[] yuiCssArgs;

	public static List<FileEntity> compressAll(String rootPath) {
		yuiJsArgs = new String[8];
		yuiJsArgs[0] = "";
		yuiJsArgs[1] = "--type";
		yuiJsArgs[2] = "js";
		yuiJsArgs[3] = "--charset";
		yuiJsArgs[4] = "utf-8";
		yuiJsArgs[5] = "--nomunge";
		yuiJsArgs[6] = "-o";
		yuiJsArgs[7] = "";

		yuiCssArgs = new String[7];
		yuiCssArgs[0] = "";
		yuiCssArgs[1] = "--type";
		yuiCssArgs[2] = "css";
		yuiCssArgs[3] = "--charset";
		yuiCssArgs[4] = "utf-8";
		yuiCssArgs[5] = "-o";
		yuiCssArgs[6] = "";

		List entities = new ArrayList();

		FileScanner.scan(rootPath, new String[] { "js", "css" }, new JsCssScanBack(rootPath, entities));

		return entities;
	}

	static class JsCssScanBack implements FileScanner.ScanCallback {
		private String webRootPath;
		private List<FileEntity> fileEntities;

		public JsCssScanBack(String rootPath, List<FileEntity> entity) {
			this.webRootPath = rootPath;
			if (!this.webRootPath.endsWith(File.separator)) {
				this.webRootPath += File.separator;
			}
			this.fileEntities = entity;
		}

		public void invoke(File file) {
			try {
				String fileName = file.getName();

				File minFile = getCompressFile(file.getAbsolutePath());
				/*if (minFile.exists())
					minFile.delete();*/

				FileEntity fe = new FileEntity();
				fe.fileName = getWebPath(file.getAbsolutePath());
				fe.minFileName = getWebPath(minFile.getAbsolutePath());

				if (fileName.toLowerCase().endsWith(".js")) {
					JsCssCompressor.yuiJsArgs[0] = file.getAbsolutePath();
					JsCssCompressor.yuiJsArgs[7] = minFile.getAbsolutePath();

					YUICompressor.main(JsCssCompressor.yuiJsArgs);
				} else if (fileName.toLowerCase().endsWith(".css")) {
					JsCssCompressor.yuiCssArgs[0] = file.getAbsolutePath();
					JsCssCompressor.yuiCssArgs[6] = minFile.getAbsolutePath();

					YUICompressor.main(JsCssCompressor.yuiCssArgs);
				}

				fe.version = String.valueOf(minFile.length());

				minFile = null;
				file = null;

				this.fileEntities.add(fe);
			} catch (Exception e) {
			}
		}

		private File getCompressFile(String oldFileName) {
			int index = oldFileName.lastIndexOf(".");

			return new File(oldFileName.substring(0, index) +  oldFileName.substring(index));
		}

		private String getWebPath(String fileName) {
			String webFileName = fileName.substring(this.webRootPath.length());
			return "/" + webFileName.replaceAll("\\\\", "\\/");
		}
	}
}

 

分享到:
评论

相关推荐

    javascript合并压缩的jsp tag实现

    JavaScript 合并压缩的 JSP Tag 实现是一个常见的前端优化技术,主要目的是为了减少网络请求次数,提升网页加载速度。在网页开发中,通常会有多份 JavaScript 文件,每份文件都对应一个网络请求,这会增加页面加载...

    UglifyJS压缩js文件和jsp里面的js代码

    在Java Web应用中,`src/main/js`可能是存放未压缩的JavaScript文件的地方,而`src/main/webapp`可能包含了JSP(JavaServer Pages)文件。在Maven构建过程中,UglifyJS会读取这些源文件,进行压缩,并将其输出到指定...

    基于yuicompressor压缩js、css、scss、html、jsp

    方法:Monitoring.init 初始化基本参数: suffix : 压缩的后缀,如min,common.js压缩后为common.min.js,html与jsp不参与 filterDir:过滤目录,正则表达式,如(./common/.)|(.\\common\\.) 为过滤包含common文件夹...

    web容器文件压缩 tk-filter tk-filter js,jsp,css,文件压缩包含源代码

    在Web开发中,为了提高网页加载速度和优化用户体验,经常需要对JavaScript(js)、JavaServer Pages(jsp)和样式表(css)等静态资源进行压缩。`tk-filter` 是一个针对这种需求设计的过滤器(Filter),它适用于...

    js压缩gzip格式

    JavaScript(JS)是一种广泛应用于网页和网络应用的编程语言,对于优化网站性能至关重要。当JS文件较大时,加载时间会增加,可能导致用户感知到的延迟。为了提高网页加载速度和用户体验,开发者通常会采用压缩技术,...

    网页弹框框架jsp+js+css

    在本项目中,我们看到的"网页弹框框架jsp+js+css"是一个使用JSP、JavaScript和CSS技术构建的弹窗解决方案。这个框架允许开发者通过简单的操作在网页上实现点击按钮后弹出新窗口的效果。 首先,JSP(JavaServer ...

    管理系统 jsp 页面模板 (干净实用) 有js

    这个标题表明我们讨论的是一个基于JSP技术的管理系统的页面模板,其中包含了JavaScript(js)进行前端验证。JSP(JavaServer Pages)是Java平台上的一种服务器端脚本语言,用于创建动态网页。它允许开发者将HTML、...

    jsp.war.rar_JSP.w_javascript_jsp war_jsp.war_jsp登陆

    在【压缩包子文件的文件名称列表】中,"2.jsp"可能是登录页面的实现,而"www.pudn.com.txt"可能是一个文本文件,其中可能包含了项目的相关信息,比如开发者的注释、版权信息或者是引用的外部资源链接。 总的来说,...

    jsp网上商城jsp课程设计

    在JSP中,开发者通常利用HTML、CSS和JavaScript来设计用户界面,同时结合Java代码来处理服务器端逻辑。这个课程设计的目标可能是为了让学生熟悉Web开发流程,了解如何使用JSP来实现动态网页功能。 【描述】提到,这...

    jspSmartUpload组件zip压缩版

    2. **创建上传页面**:在JSP页面中添加`jspSmartUpload`的JavaScript和CSS引用,以及上传按钮和隐藏的表单元素。 3. **编写后台处理**:在Servlet或Action类中处理上传请求,使用`jspSmartUpload`API解析上传数据,...

    一个Jsp弹出窗口

    在这个"一个Jsp弹出窗口"的例子中,我们可以假设它主要依赖于JavaScript来处理用户的交互,并利用JSP的后端能力来处理数据或逻辑。 首先,我们需要了解JSP页面的基本结构。一个典型的JSP页面由HTML标记、JSP指令和...

    jsp实现计算器--韩顺平

    从【压缩包子文件的文件名称列表】"jsp计算器"来看,可能包含的文件有: 1. `calculator.jsp`:主页面,可能包含了输入字段、按钮和计算结果的显示区域。 2. `calculate.jsp`或`process.jsp`:处理计算逻辑的后端...

    jsp图片轮播html

    5. **js**:这个文件夹包含了JavaScript代码,很可能包含了图片轮播的控制逻辑,如定时器控制自动轮播,点击事件处理图片切换等。 6. **css**:CSS文件夹包含样式表,用于定义图片轮播的外观和布局,比如图片大小、...

    jsp.zip_javascript BBS_jsp bbs

    【标题】"jsp.zip_javascript BBS_jsp bbs" 提供的是一个基于JSP2.0技术构建的论坛系统,结合了JavaScript的功能,用于增强用户交互性。这个项目不仅包含了论坛系统的源代码,还涉及到了数据库的设计和管理,旨在为...

    jsp中的JS 时间控件

    - 缓存与压缩:合并和压缩JS资源,利用HTTP缓存,提高页面加载速度。 总之,JSP中的JS时间控件是提高用户交互性和页面功能的重要手段,通过选择合适的库并进行适当的定制,可以实现高效、易用的时间选择功能。同时...

    jsp 精美版面与代码

    【JSP精美版面与代码】的学习资源是一个宝贵的资料库,尤其对于初学者或希望提升JSP页面设计技能的开发者来说。...同时,也要不断学习新的Web技术,如Spring Boot、React或Vue.js,以适应不断变化的开发环境。

    jsp 企富商贸网jsp 企富商贸网

    2. **js11qfsyw**:这个文件名看起来像是一个被截断的JSP文件或JavaScript文件,但无法确定具体功能。在JSP应用中,这样的文件可能包含了页面逻辑或者前端交互脚本,比如用户验证、数据检索等功能。 在JSP应用开发...

    BigDecimal.js.zip

    "min.js"通常表示经过压缩和混淆处理,以便在生产环境中更高效地使用,同时不影响库的功能。 BigDecimal.js库的核心功能在于提供了大数运算的方法,如加法、减法、乘法、除法,以及比较、取模、平方根等操作。它还...

    JS、CSS合并压缩工具说明

    JS、CSS 合并压缩工具是用于优化前端资源加载效率的重要工具,它们能够将多个 JavaScript 和 CSS 文件合并为一个文件,并进行压缩,减少网络请求次数,从而提高网页加载速度。本篇将详细介绍名为 TomsTools 的一套 ...

Global site tag (gtag.js) - Google Analytics