我想做的是通过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)"