参考文档:菜鸟教程:http://www.runoob.com/
转载文档:http://www.cnblogs.com/zmjh/p/8886905.html
请求jsp页面:index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>zmjh_time</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"> </head> <body> <input type="text" name="time" value="当前时间:" readonly="true"/> <input type="text" name="time" value="" id="time" readonly="true"/> <script type="text/javascript" language='javascript'> function timee() { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");//IE } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200)//请求成功 { document.getElementById("time").value=xmlhttp.responseText; } } xmlhttp.open("GET","time?canshu=time",true); //xmlhttp.open("GET","time.jsp?canshu=time",true); xmlhttp.send(); } window.setInterval("timee()",1000); </script> </body> </html>
被请求的jsp页面:time.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <%@ page import="java.io.*" %> <%@ page import="java.text.SimpleDateFormat" %> <%@ page import="java.util.Date" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>zmjh_time</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"> </head> <body> <% Date day=new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); response.getWriter().println(df.format(day)); %> </body> </html>
被请求的servlet页面:time.java:
import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class time extends HttpServlet { public time() { super(); } public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); if(request.getParameter("canshu").equals("time")){ Date day=new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); out.println(df.format(day)); }else{ response.setStatus(400, "你请求的不是时间,因此不能响应!"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } public void init() throws ServletException { } }