JavaScript dynamically gets server time
Many Java Web applications need to obtain server time dynamically, such as the company's attendance system, ticket booking system and so on. The renderings are as follows:
How to achieve it?
Preparation
Eclipse creates a new Dynamic Web Project, in this case, ShowTime
Remember to check the Generate web.xml deployment descriptor check box:
Front end
Create a new index.jsp in the WebContent directory, first draw the area to display the current time, and then add a function to get the server time regularly. For details of each step, see the note. The complete code in index.jsp is as follows:
<%@ 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() { //Judge whether http interaction is successful if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //Get the data (string) returned by the server, find the element node corresponding to the div tag through dom, set the value of the element node, and display the data on the page document.getElementById("time").value = xmlhttp.responseText; } } //Create a new http request and specify the request mode. The three parameters set the request mode in turn, url, synchronous (false) or asynchronous (true). Where? Is followed by the passed variable xmlhttp.open("GET","TimeServlet?parameter=times",true); //Send request to server xmlhttp.send(); } //Call function according to specified period (unit: ms) window.setInterval("showTime()", 1000); </script> </body> </html>
Backstage
The front-end work is ready, and then write to the background. Create a new package redburning.ServletStudy in src directory, and a new Servlet named TimeServlet in the package. (Note: there is an unwritten rule that the name of a Servlet usually ends with 'Servlet')
In the generated TimeServlet.java implementation, the time of the server is passed to the front end. The complete code is as follows:
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."); } }
The complete catalog of the project is as follows:
Run on server, enter http://localhost:8080/ShowTime/ , the screenshot of operation effect is as follows: