/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import javax.servlet.http.*; import javax.servlet.*; import javax.servlet.annotation.*; import javax.swing.*; import java.awt.event.*; import java.util.Date; /** * * @author Administrator */ @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) { System.out.println(new Date()); } }); t.start(); } }
<?xml version="1.0" encoding="UTF-8"?> <web-app metadata-complete="true" version="3.1" 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"> <!-- 配置Servlet的名字 --> <servlet> <!-- 指定Servlet的名字, 相当于指定@WebServlet的name属性 --> <servlet-name>firstServlet</servlet-name> <!-- 指定Servlet的实现类 --> <servlet-class>FirstServlet</servlet-class> </servlet> <!-- 配置Servlet的URL --> <servlet-mapping> <!-- 指定Servlet的名字 --> <servlet-name>firstServlet</servlet-name> <!-- 指定Servlet映射的URL地址, 相当于指定@WebServlet的urlPatterns属性--> <url-pattern>/aa</url-pattern> </servlet-mapping> <servlet> <!-- Servlet名 --> <servlet-name>timerServlet</servlet-name> <!-- Servlet的实现类 --> <servlet-class>TimerServlet</servlet-class> <!-- 配置应用启动时,创建Servlet实例 ,相当于指定@WebServlet的loadOnStartup属性--> <load-on-startup>1</load-on-startup> </servlet> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>