如何在Javascript中动态调用Java函数?

huangapple go评论73阅读模式
英文:

How to call Java function dynamically from Javascript?

问题

我开始学习JSP,所以我想在JSP上使时间显示动态化。

我创建了一个名为Times的类

public class Times {
    DateTimeFormatter dtf = null;
    LocalDateTime now = null;
    public Times() {
         dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");  
    }
    public String getTime() {
         now = LocalDateTime.now(); 
         return dtf.format(now);
    }
}

我在JSP文件中调用了getTime函数

<%@ page import="data.Times"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script type="text/javascript">
    var time = "";
    function showTime() {
        <%
            Times t = new Times();
        %>
        time = '<%=t.getTime()%>';
    }
    function startTime() {
        showTime();
        document.getElementById('time').innerHTML = time;
        t = setInterval(function () {
            startTime()
        }, 500);
    }
</script>
<style>
    @font-face{
        font-family: clock;
        src: url(content/digital-7.ttf)
    }
    #time{
        width: 100%;
        margin: 0 auto;
        font-family: clock;
        font-size: 100px;
    }
</style>
</head>
<body onload="startTime()">
    <div id="time" align="center">
    </div>
</body>
</html>

但问题是页面加载后,时间被初始化,但保持不变。

如果我刷新页面,时间会正确改变。

我可以以动态方式更改时间吗?

英文:

I started to learn JSP, so I want to make displaying time dynamic on JSP.

I created a class Times

public class Times {
    DateTimeFormatter dtf =null;
    LocalDateTime now =null;
    public Times()
    {
         dtf = DateTimeFormatter.ofPattern(&quot;yyyy/MM/dd HH:mm:ss&quot;);  
    }
    public String getTime()
    {
         now = LocalDateTime.now(); 

        return dtf.format(now);
    }
    
   
}

I call getTime function in the JSP file

&lt;%@ page import=&quot;data.Times&quot;%&gt;

&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;
    pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;&lt;/title&gt;
&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js&quot;&gt;&lt;/script&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
   
    var time=&quot;&quot;;
    function showTime(){
        &lt;%
            Times t=new Times();
        %&gt;
           time = &#39;&lt;%=t.getTime()%&gt;&#39;;
    }
    function startTime() {
        showTime();
        document.getElementById(&#39;time&#39;).innerHTML =time;
        t = setInterval(function () {
            startTime()
        }, 500);
        }
&lt;/script&gt;
&lt;style&gt;
    @font-face{
        font-family: clock;
        src:url(content/digital-7.ttf)
    }
    #time{
        width: 100%;
        margin: 0 auto;
        font-family: clock;
        font-size: 100px;
    }
&lt;/style&gt;
&lt;/head&gt;
&lt;body onload=&quot;startTime()&quot;&gt;
    &lt;div id=&quot;time&quot; align=&quot;center&quot;&gt;
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;

But the problem is that the page is loaded, however, time is initialized but it remains unchanged.

If I refresh the page, time is properly changed.
Can I change time dynamic way ?

答案1

得分: 1

基本上您有两个主要选项:

AJAX

可以使用AJAX向后端发送请求。在后端,您可以响应这些AJAX请求并提供时间,然后在回调中刷新时间值。

仅在客户端执行

您还可以基于从服务器接收的时间创建一个日期对象并进行调整。但我想您更加关注AJAX解决方案。

进一步解释

您的代码目前向浏览器发送一个页面,其中时间在初始计算时是正确的。您的setInterval调用了showTime函数,但&lt;% = t.getTime()%&gt;在页面发送出去之前在服务器上进行了评估。如果您打算从服务器获取信息,则需要与服务器建立进一步的通信。例如通过AJAX。

英文:

Basically you have two main options:

AJAX

AJAX can be used in order to send a request to your backend. On your backend you could respond to these AJAX requests with the time and then in the callback refresh the time value.

Doing only on the client-side

You can also create a Date object based on the time received from the server and adjust it. But I suppose that you are more interested in the AJAX solution

Further explanation

Your code currently sends a page to the browser where the time is properly calculated initially. Your setInterval calls showTime, but &lt;%=t.getTime()%&gt; was evaluated at the server before the page was sent out. You need to establish further communication with your server if you intend to get information from there. Via AJAX, for example.

答案2

得分: 1

当您显示该页面时,JSP 在服务器上执行一次,这意味着 t.getTime() 会执行一次。

如果您在 Web 浏览器中执行“查看源代码”,您会看到服务器生成了以下内容:

&lt;script type=&quot;text/javascript&quot;&gt;

    var time=&quot;&quot;
    function showTime(){
           time = &#39;2020/03/03 17:47:45&#39;;
    }
    function startTime() {
        showTime();
        document.getElementById(&#39;time&#39;).innerHTML =time;
        t = setInterval(function () {
            startTime()
        }, 500);
        }
&lt;/script&gt;

正如您所见,time 的值现在固定为服务器处理 JSP 时的日期/时间。重复调用 showTime() 不会改变 time 的值。

如果您想要时间值是“实时”的,您需要在 JavaScript 代码中实现,而不是在 JSP 代码中。

以下是一种实现方式,基于问题“将 JavaScript 日期格式化为 yyyy-mm-dd”的此答案

    function showTime() {
        const date = Date.now();
        time = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
                .toISOString()       // yyyy-MM-ddTHH:mm:ss.SSSZ
                .replace(/\..*/, &#39;&#39;) // yyyy-MM-ddTHH:mm:ss
                .replace(/T/, &#39; &#39;)   // yyyy-MM-dd HH:mm:ss
                .replace(/-/g, &#39;/&#39;); // yyyy/MM/dd HH:mm:ss
    }
英文:

When you display that page, the JSP is executed once on the server, which means that t.getTime() is executed once.

If you do a "View Source" in the web browser, you'll see that the server has generated the following:

&lt;script type=&quot;text/javascript&quot;&gt;

    var time=&quot;&quot;;
    function showTime(){
           time = &#39;2020/03/03 17:47:45&#39;;
    }
    function startTime() {
        showTime();
        document.getElementById(&#39;time&#39;).innerHTML =time;
        t = setInterval(function () {
            startTime()
        }, 500);
        }
&lt;/script&gt;

As you can see, the value of time is now fixed at the date/time the server processed the JSP. Calling showTime() repeatedly will not change the value of time.

If you want the time value to be "live", you need to do this in JavaScript code, not JSP code.

Here is a way to do it, based on this answer to question "Format JavaScript date as yyyy-mm-dd":

    function showTime() {
        const date = Date.now();
        time = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
                .toISOString()       // yyyy-MM-ddTHH:mm:ss.SSSZ
                .replace(/\..*/, &#39;&#39;) // yyyy-MM-ddTHH:mm:ss
                .replace(/T/, &#39; &#39;)   // yyyy-MM-dd HH:mm:ss
                .replace(/-/g, &#39;/&#39;); // yyyy/MM/dd HH:mm:ss
    }

答案3

得分: 1

time remains unchanged unless page invoked. in order to call dynamically try to refresh it for specified interval like below , include it in <head> </head>

<meta http-equiv="refresh" content="5" >
英文:

time remains unchanged unless page invoked. in order to call dynamically try to refresh it for specified interval like below , include it in &lt;head&gt; &lt;/head&gt;

&lt;meta http-equiv=&quot;refresh&quot; content=&quot;5&quot; &gt;

huangapple
  • 本文由 发表于 2020年3月4日 06:37:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/60516553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定