Thursday, May 28, 2009

Get Current Server Time on Client JSP Page using Ajax

Using AJAX, you can show the server current time on client page. Time would be update on every second. Even you can set the interval of fetching time from server.

For example I am showing one jsp page and servlet.
To use this tutorial, no need to download any jar file or extra files.
Just make one dynamic web project and use this jps and servlet file.

1. ShowServerTime.jsp

<title>Binod Java Solution AJAX </title>

<script type="text/javascript">
var request;
function init(){
function getTime(){
var url = "http://localhost:8080/ServerTime/GetServerTime";
request = new ActiveXObject("Microsoft.XMLHTTP");
else if(window.XMLHttpRequest){
request = new XMLHttpRequest();
request.onreadystatechange = showTime;"POST",url,true);

function showTime(){

if(request.readyState == 4){
var response = request.responseText;
document.getElementById("TimeH1").innerHTML = response;



<body onload="init();">
<h1> Server Time :: </h1> <h1 id="TimeH1"/>


2. (This is a servlet file)

import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetServerTime extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print(new Date());


  1. Got to here from site. It was worth it.

  2. can you tell me why i had seach in javax. but haven't servlet.
    i'm just start learning java so everything to me it's very new,so please help me.

  3. Swing supports data transfer through drag and drop, copy-paste, cut-paste etc. Data transfer works between Swing components within an application and between Java and native applications. The ability of data transfer is beneficial to programs between Java applications, between components etc.

  4. why is this interval set to 1000ms.can't it be 0.and if it can be then y so?


You can put your comments here (Either feedback or your Question related to blog)