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("yyyy/MM/dd HH:mm:ss");
}
public String getTime()
{
now = LocalDateTime.now();
return dtf.format(now);
}
}
I call getTime
function in the JSP file
<%@ 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>
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 ?