Skip to content Skip to sidebar Skip to footer

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 charact

Solution 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.

Solution 2:

Client JavaScript/ECMAScript:

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

Server Java:

Stringcookie_value= java.net.URLDecoder.decode(cookie.getValue());

I'll add further discoveries to my blog entry.

Solution 3:

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

ScriptEngineManagerfactory=newScriptEngineManager();
   ScriptEngineengine= factory.getEngineByName("JavaScript");
   ScriptContextcontext= engine.getContext();
   engine.eval("function decodeStr(encoded){"
             + "var result = unescape(encoded);"
             + "return result;"
             + "};",context);

     Invocable inv;   

    inv = (Invocable) engine;
    Stringres=  (String)inv.invokeFunction("decodeStr", newObject[]{cookie.getValue()});

Solution 4:

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

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

privateStringdecodeJavascriptString(final String encodedString) {
    ScriptEngine engine = newScriptEngineManager().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;
}

Post a Comment for "Un-escape Javascript Escaped Value In Java"