JavaScript动态获取服务器时间

本文介绍了一种使用JavaScript和Servlet动态获取服务器时间的方法,适用于JavaWeb应用如考勤系统和车票预订系统。通过定时调用后端Servlet,前端能够实时更新显示服务器当前时间。

JavaScript动态获取服务器时间

 

很多Java Web应用程序需要动态获取服务器时间,例如公司的考勤系统,车票预订系统等等。效果图如下:

如何实现呢?

准备工作

Eclipse新建Dynamic Web Project,本例命名为ShowTime.

记得勾选Generate web.xml deployment descriptor复选框:

前端

WebContent目录下新建index.jsp,首先绘制待显示当前时间的区域,接下来添加用于定时获取服务器时间的函数,每一步的细节详见注释。index.jsp中的完整代码如下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Show Time</title>
</head>
<body>
    <form style = "text-align:center">
        <br>
	<label style = "font-size:30px; color:blue; margin-top:50px; font-style:italic; font-family:times">Current Time:</label>
	<input type="text" name="time" value="" id="time" style = "font-size:30px; color:blue; font-style:italic; font-family:times" readonly="true"/>
	<br>
	<img alt="" src="image/time.jpg" width = 480>
    </form>
    <script type="text/javascript" language='javascript'>
	function showTime(){
	    var xmlhttp;
	    if (window.XMLHttpRequest){
	        xmlhttp = new XMLHttpRequest();
	    }
	    else{
	        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//IE
	    }
	    xmlhttp.onreadystatechange = function(){
	        //判断http交互是否成功
	    	if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
	            //获取服务器端返回的数据(字符串),并通过dom方式找到div标签所对应的元素节点,设置元素节点的value,将数据显示在页面上
	    	    document.getElementById("time").value = xmlhttp.responseText;
	        }
	    }
	    //创建新的http请求,并规定请求的方式.三个参数依次设置请求的方式,url,同步(false)或者异步(true).其中?后面为传递的变量
	    xmlhttp.open("GET","TimeServlet?parameter=times",true);
	    //将请求发送到服务器
	    xmlhttp.send();
	}
	//按照指定周期(单位ms)调用函数
	window.setInterval("showTime()", 1000);
    </script>
</body>
</html>

后台

前端工作准备就绪,接下来写后台。在src目录下新建包redburning.ServletStudy,在包中新建一个servlet,命名为TimeServlet。(注:这里有一个不成文的规定,Servlet的名称一般以''Servlet''结尾

在生成的TimeServlet.java实现将服务器的时间传给前端,完整代码如下:

package redburning.ServletStudy;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;
import java.text.SimpleDateFormat;

/**
 * Servlet implementation class TimeServlet
 */
@WebServlet("/TimeServlet")
public class TimeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TimeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    /**
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());
        if(request.getParameter("parameter").equals("times")){
            Date date = new Date();    
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
            response.getWriter().append(df.format(date));   
        }else{
            response.getWriter().append("error!");
        }
        System.out.println("get time.")
    }
    /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
        System.out.println("post time.");
    }

}

工程的完整目录如下图:

Run on server,在浏览器中输入http://localhost:8080/ShowTime/,运行效果截图如下:

源程序下载链接:https://download.youkuaiyun.com/download/lanshanzhuyao/10690029

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值