Java obtains the server time and dynamically displays it on the jsp page. It is only available once in Java and the page time is static. However, through cooperation between js and Java, cleverly implement this function.
I am working on a TV system. The customer asked the page to display the time. Because the time obtained by the TV browser is incorrect, I can't just get the time from the server, but the problem arises, once the server is acquired, it becomes static. The customer is not satisfied, but there is no way to do this. However, I remember this question. Today I see an example that I want to convert the time for obtaining the server from Java to milliseconds. Then I can use js to refresh the server every second to display it dynamically, so we have the following
Copy codeThe Code is as follows:
<% @ Page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %>
<% @ Page import = "java. text. SimpleDateFormat;" %>
<%
String path = request. getContextPath ();
String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/";
%>
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Base href = "<% = basePath %>">
<Title> My JSP 'index. jsp 'starting page </title>
<Meta http-equiv = "pragma" content = "no-cache">
<Meta http-equiv = "cache-control" content = "no-cache">
<Meta http-equiv = "expires" content = "0">
<Meta http-equiv = "keywords" content = "keyword1, keyword2, keyword3">
<Meta http-equiv = "description" content = "This is my page">
<! --
<Link rel = "stylesheet" type = "text/css" href = "styles.css">
-->
</Head>
<Body>
<%
Calendar rightNow = Calendar. getInstance ();
SimpleDateFormat format = new SimpleDateFormat ("yyyy-MM-dd HH: mm ");
%>
<Script language = "javascript">
// Obtain the initial time from the server
Var currentDate = new Date (<% = new java. util. Date (). getTime () %> );
Function run ()
{
CurrentDate. setSeconds (currentDate. getSeconds () + 1 );
Var time = "";
Var year = currentDate. getFullYear ();
Var month = currentDate. getMonth () + 1;
Var day = currentDate. getDate ();
Var hour = currentDate. getHours ();
Var minute = currentDate. getMinutes ();
Var second = currentDate. getSeconds ();
If (hour <10 ){
Time + = "0" + hour;
} Else {
Time + = hour;
}
Time + = ":";
If (minute <10 ){
Time + = "0" + minute;
} Else {
Time + = minute;
}
Time + = ":";
If (second <10 ){
Time + = "0" + second;
} Else {
Time + = second;
}
Document. getElementById ("dt"). innerHTML = year + "year" + month + "month" + day + "day" + time;
}
Window. setInterval ("run ();", 1000 );
</Script>
<Div id = "dt"> auto display time .... </Div>
</Body>
</Html>