简体   繁体   English

在freemarker模板中从javascript调用Java类的方法

[英]Calling Java class's method from javascript in a freemarker template

I have a freemarker template with javascript in it, and I'm using spring mvc to pass in a java object "emailer". 我有一个带有javascriptfreemarker模板,并且我正在使用spring mvc传递一个Java对象“ emailer”。

Somehow, in this freemarker template, I want to call the emailer object's "sendEmail(params, ..)" method from javascript within the freemarker template. 不知何故,在这个freemarker模板中,我想从freemarker模板中的javascript调用emailer对象的“ sendEmail(params,..)”方法。 I know how to call java methods from freemarker (the regular way - for example: How do I call java methods on an object from a FreeMarker template? ) , but I don't know how to do it from within the javascript . 我知道如何从freemarker调用Java方法(常规方法-例如: 如何从FreeMarker模板调用对象上的Java方法? ),但我不知道如何从javascript中进行操作

Is this even possible? 这有可能吗? If so, how? 如果是这样,怎么办? And if it's not, what are some alternatives? 如果不是,那么还有哪些替代方案?

The overall goal was to get a value from a dropdown list (using javascript), and then using that value in the java method that gets called when a button is pressed. 总体目标是从下拉列表中获取一个值(使用javascript),然后在按下按钮时调用的java方法中使用该值。

Thanks in advance! 提前致谢! If more info is needed, I'd be happy to provide it. 如果需要更多信息,我很乐意提供。

It's not the only possible combination of how these technologies would work together, but in the usual flow of things, what you're looking forward wouldn't be possible: 这不是这些技术如何协同工作的唯一可能的组合,但是在通常的情况下,您所期待的是不可能的:

  • A Java call (mediated with Spring ) renders the FreeMarker , allowing calls back into Java code as it processes. Java调用(由Spring介导)呈现FreeMarker ,从而允许在处理过程中将其调用回Java代码。
  • This rendered string (which might happen to contain some Javascript ) is shipped over HTTP to the client browser. 此呈现的字符串(可能恰好包含一些Javascript )通过HTTP传送到客户端浏览器。 At this point the Java execution has completed. 至此Java执行已经完成。
  • In the browser, the generated text is parsed, and the Javascript is run. 在浏览器中,将解析生成的文本,然后运行Javascript Here there is no direct knowledge of the server, and there is no way to call back that completed thread of control. 这里没有服务器的直接知识,也没有办法回调完成的控制线程。

So unless you're doing something more unusual, no you can't do what you're suggesting. 因此,除非您要执行更不寻常的操作,否则您就无法按照您的建议去做。

There are tools to allow client-side Javascript to call back to the server and to interact with Java there.; 有一些工具可以使客户端Javascript回调到服务器并在其中与Java进行交互。 so you can rig something up. 这样您就可以装配一些东西。 But you will not simply call the Java directly without more work. 但是,您无需做更多工作就不会直接直接调用Java。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM