java读取js文件

/**
* 获取js中随机产生url参数的方法
* @author w
* @return
* @throws Exception
*/

public static String testScriptVariables() throws Exception {

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
String res = null;
try {
String script = "function genT() {\n"
       + "            var sig = \"\";\n"
       + "            var chars = \"0123456789abcdef\";\n"
       + "            if(true){\n"
       + "                var curTime = parseInt(Math.random()*(9999-1000+1)+1000)+\"\"+Date.parse(new Date());\n"
       + "                sig = chars.charAt(parseInt(Math.random()*(15-15+1)+10))+chars.charAt(curTime.length)+\"\"+curTime;\n"
       + "            }else{\n"
       + "                sig = __signature;\n"
       + "            }\n"
       + "\n"
       + "            var key = \"\";\n"
       + "            var keyIndex = -1;\n"
       + "            for(var i=0;i<6;i++){\n"
       + "                var c=sig.charAt(keyIndex+1);\n"
       + "                key +=c;\n"
       + "                keyIndex = chars.indexOf(c);\n"
       + "                if(keyIndex<0 || keyIndex>=sig.length){\n"
       + "                    keyIndex = i;\n"
       + "                }\n"
       + "            }\n"
       + "\n"
       + "\t\t\tvar curUrl='';\n"
       + "            var timestamp = parseInt(Math.random()*(9999-1000+1)+1000)+\"_\"+key+\"_\"+Date.parse(new Date());\n"
       + "            var t = timestamp;\n" + "            t = t.replace(/\\+/g,\"_\");\n"
       + "            curUrl+= \"?s=\" + sig;\n" + "            curUrl+= \"&t=\" +  t;\n"
       + "\t\t\treturn curUrl;\n" + "        }";
engine.eval(script);
Invocable inv2 = (Invocable)engine;
res = (String)inv2.invokeFunction("genT");
System.out.println("当前结果为:" + res);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}

你可能感兴趣的:(java读取js文件)