java中执行JS脚本
package 测试包; import javax.script.*; public class SSSSSSSSS { public SSSSSSSSS() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub ScriptEngineManager sem=new ScriptEngineManager(); ScriptEngine se=sem.getEngineByName("javascript"); try{se.eval("var a=3;var b=4;print(a+b)"); //执行js代码 }catch(Exception e){e.printStackTrace();} } }
补充:今天在后台想对URL进行编码,URL中有参数
String url = "http://www.baidu.com?param=中国";
System.out.println(URLEncoder.encode(url));
结果: (对一些特殊字符,比如// ? & 也进行转义)
http%3A%2F%2Fwww.baidu.com%3Fparam%3D%E4%B8%AD%E5%9B%BD
于是想到在Java中调用JS的encodeURI()方法:
package cn.xm.exam.test; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PlainTest { private static final Logger LOGGER = LoggerFactory.getLogger(PlainTest.class); public static void main(String[] args) { String url = "http://www.baidu.com?param=中国"; System.out.println(encodeURI(url)); } public static String encodeURI(String url) { if ("".equals(url)) { return ""; } ScriptEngineManager sem = new ScriptEngineManager(); ScriptEngine se = sem.getEngineByName("javascript"); String jsCommand = "encodeURI('" + url + "');"; LOGGER.debug("jsCommand -> {}", jsCommand); try { String result = (String) se.eval(jsCommand); // 执行js代码 return result; } catch (Exception e) { LOGGER.error("encodeURI error,jsCommand ->{}", jsCommand, e); return ""; } } }
结果:
http://www.baidu.com?param=%E4%B8%AD%E5%9B%BD
【当你用心写完每一篇博客之后,你会发现它比你用代码实现功能更有成就感!】