在 Java 中压缩和混淆 JavaScript 代码 [英] Minify and obfuscate JavaScript code in Java

查看:61
本文介绍了在 Java 中压缩和混淆 JavaScript 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我多年来一直使用 YUI Compressor 来缩小和混淆 JS 文件.但现在我需要混淆和缩小服务器上动态生成的 JavaScript 代码.所以这里的主要区别是不会有应该混淆的 JS 文件,而是对服务器 (Java) 的请求,它应该生成部分 JS 代码并返回它们已经被缩小和混淆.

I use YUI Compressor for years to minify and obfuscate JS files. But now I need to obfuscate and minify dynamically generated JavaScript code on the server. So the main difference here is that there will not be JS files that should be obfuscated but requests to the server (Java) which should generate portions of JS code and return them already minified and obfuscated.

YUI Compressor 不提供这样做的可能性.我查看了源代码,并且已经弄清楚应该覆盖哪些方法才能使其工作.我不想这样做(但在没有其他方法的情况下必须这样做).

YUI Compressor does not give the possibility to do that. I watched in the sources and have already figured out what methods should be overridden to make it work. I would not like to do this (but will have to in case there is no other way).

那么有没有其他 Java 库允许直接从 Java 代码中缩小和混淆 JavaScript 字符串?

So are there any other Java libraries allowing to minify and obfuscate JavaScript strings directly from Java code?

推荐答案

Plan a)

不要将 YUI 用作命令行工具,而是将其用作 Java 库并在您的代码中调用它.

Use the YUI not as a command line tool, but as a Java library and call it in your code.

JavaScriptCompressor 接受 Reader 后代(例如 InputFileReader).

The JavaScriptCompressor accepts a Reader descendant (e.g. InputFileReader).

    JavaScriptCompressor compressor = new JavaScriptCompressor(in, new YuiCompressorErrorReporter());

您实际上可以获取原始 JavaScript 并将其转换为 Stream,例如如何将字符串转换为输入流爪哇?

You can actually get your raw JavaScript and convert it to a Stream, e.g. How do I convert a String to an InputStream in Java?

完整的集成示例如下:

http://blog.teamextension.com/yui-compressor-in-java-246

计划 b)

请注意,您可以简单地将生成的 javascript 保存到文件系统中,然后从 Java 调用命令行 Yui.然后从文件系统中读取缩小后的文件,就是这样,你就有了一个缩小后的 JS.

Note that you could simply save the generated javascript into the filesystem, and call the command line Yui from Java. Then read the minified file from the filesystem, and that's it, you have a minified JS.

这篇关于在 Java 中压缩和混淆 JavaScript 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆