0

我想做的是通过java代码在浏览器地址栏中解析一个json对象。我想要获取的 JSON 对象应该是:

{idUtente : "idUtente"}

所以我实现了这段代码

public void inviaMailConferma(Utente utente) throws Exception {

    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(utente.getEmail());
    message.setSubject("Conferma registrazione a Portfolio Online");
    InetAddress ip = InetAddress.getLocalHost();
    ScriptEngineManager factory = new ScriptEngineManager();
    ScriptEngine engine = factory.getEngineByName("JavaScript");
    String idUtente = utente.getUsername();
    Object eval = engine.eval("print(encodeURIComponent(idUtente))");
    message.setText("Ciao " + utente.getUsername() + "! Per registrarsi al sito, cliccare il seguente link: " + ip.getHostAddress() + ":8084/VenditaGioielli/confermaRegistrazione?data=" + eval.toString());
    mailSender.send(message);

}

当我运行engine.eval 时,我遇到了这个异常

ex = (javax.script.ScriptException) javax.script.ScriptException:
sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "idUtente" is not
defined. (<Unknown source>#1) in <Unknown source> at line number 1

我不知道如何将 java 对象解析为 engine.val!

编辑

现在我来到了这个代码

 ScriptEngine engine = factory.getEngineByName("JavaScript");
 String idUtente = utente.getUsername();
 engine.put("idUtente", idUtente);
 Object eval = engine.eval("print(encodeURIComponent(idUtente))");

但engine.eval 返回null!

编辑

现在我来到这个代码

 ScriptEngineManager factory = new ScriptEngineManager();
 ScriptEngine engine = factory.getEngineByName("JavaScript");
 ScriptContext scriptContext = new SimpleScriptContext();
 Bindings binding = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
 String idUtente = utente.getUsername();
 engine.put("idUtente", idUtente);
 Object eval = engine.eval("print(encodeURIComponent(idUtente))", binding);

我有以下例外:

"sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "idUtente" is not defined. (<Unknown source>#1)"
4

1 回答 1

0

引擎有自己的上下文,不知道是什么idUtente。只需通过engine.put("idUtente", idUtente). 那应该行得通。

我特别写了一篇关于 ScriptEngine 和绑定的博客文章:http ://wondee.info/2013/10/30/the-scriptengine-bindings/

于 2013-11-06T10:26:06.037 回答