5

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
pvgoddijn
  • 12,638
  • 15
  • 47
  • 56

4 Answers4

7

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.

Robert
  • 39,162
  • 17
  • 99
  • 152
Valentin Rocher
  • 11,667
  • 45
  • 59
  • If you want to decode from encodeURIComponent see here http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-outpu – reevesy Feb 15 '12 at 19:50
4

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.

Cees Timmerman
  • 17,623
  • 11
  • 91
  • 124
1

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()});
  • With nashorn engine, you can simply write: (String) invocable.invokeFunction("unescape", escapedString); – Shafiul Oct 29 '16 at 09:23
1

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;
}
Shafiul
  • 1,452
  • 14
  • 21