Un-escape JavaScript escaped value in Java

前端 未结 4 1525
醉梦人生
醉梦人生 2021-01-18 23:05

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 i

4条回答
  •  甜味超标
    2021-01-18 23:55

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

提交回复
热议问题