Un-escape JavaScript escaped value in Java

可紊 提交于 2019-12-01 17:18:37

问题


In our web service we set a cookie through JavaScript wich we read again in Java (Servlet)

However we need to escape the value of the cookie because it may contain illegal characters such as '&' which messes up the cookie.

Is there a transparent way to escape (JavaScript) and unescape again (Java) for this?


回答1:


In java you got StringEscapeUtils from Commons Lang to escape/unescape.

In Javascript you escape through encodeURIComponent, but I think the Commons component I gave to you will satisfy your needs.




回答2:


Client JavaScript/ECMAScript:

encodeURIComponent(cookie_value) // also encodes "+" and ";", see http://xkr.us/articles/javascript/encode-compare/

Server Java:

String cookie_value = java.net.URLDecoder.decode(cookie.getValue());

I'll add further discoveries to my blog entry.




回答3:


The most accurate way would be to Excecute javascript withing your java code. Hope the code below helps.

ScriptEngineManager factory = new ScriptEngineManager();
   ScriptEngine engine = factory.getEngineByName("JavaScript");
   ScriptContext context = engine.getContext();
   engine.eval("function decodeStr(encoded){"
             + "var result = unescape(encoded);"
             + "return result;"
             + "};",context);

     Invocable inv;   

    inv = (Invocable) engine;
    String res =  (String)inv.invokeFunction("decodeStr", new Object[]{cookie.getValue()});



回答4:


Common lang's StringEscapeUtils didn't work for me.

You can simply use javascript nashorn engine to unescape a escaped javascript string.

private String decodeJavascriptString(final String encodedString) {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    Invocable invocable = (Invocable) engine;
    String decodedString = encodedString;
    try {
        decodedString = (String) invocable.invokeFunction("unescape", encodedString);

    } catch (ScriptException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

    return decodedString;
}


来源:https://stackoverflow.com/questions/882036/un-escape-javascript-escaped-value-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!