Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Un-escape JavaScript escaped value in Java

In our web service we set a cookie through JavaScript which 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?

like image 938
pvgoddijn Avatar asked May 19 '09 10:05

pvgoddijn


4 Answers

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.

like image 197
Valentin Rocher Avatar answered Oct 28 '22 13:10

Valentin Rocher


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.

like image 36
Cees Timmerman Avatar answered Oct 28 '22 13:10

Cees Timmerman


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()});
like image 29
Eudy Sekgota Avatar answered Oct 28 '22 13:10

Eudy Sekgota


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;
}
like image 37
Shafiul Avatar answered Oct 28 '22 11:10

Shafiul