UnEscape JavaScript value in JAVA

in our web service we set a cookie using JavaScript, which we read again in Java (Servlet)

however, we need to avoid the cookie value, as it may contain illegal characters such as the '&' which ruined the cookie.

Is there a transparent way to avoid (JavaScript) and unescape again (JAVA) for this?

thank you Peter Goddiyn

+5
source share
4 answers

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

Javascript encodeURIComponent, , Commons, , .

+7

JavaScript/ECMAScript:

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

Java:

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

.

+4

- Excecute javascript java-. , .

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()});
+1

lang StringEscapeUtils .

You can just use javascript nashorn to unescape the javascript escape line.

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;
}
0
source

All Articles