JAVA
import java.awt.event.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.swing.Timer;
//@WebServlet (loadOnStartup=1)
public class TimerServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
Timer t = new Timer(1000,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = new Date();
writeTxt(sdf.format(date));
}
});
t.start();
}
public void writeTxt(String strTxt) {
BufferedWriter fw = null;
try {
File file = new File("D://log.txt");
fw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true), "UTF-8"));
fw.append(strTxt);
fw.newLine();
fw.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="true"><!--属性为true时,web应用将不会加载注解配置的web组件 metadata-complete="true"-->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>a.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>timerServlet</servlet-name>
<servlet-class>TimerServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
</web-app>