Java中如何让web服务器启动的时候自动运行web程序中某个类的某个方法

1,新建一个java的Servlet,我这里直接贴上我测试成功的脚本

package com.pinao.dao;

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;

@WebServlet("/GetComputerCode")

public class GetComputerCode extends HttpServlet {

static {

System.out.println("YYYYYYYYYYYYYYYYYYYYYYYYYYY");

}

private static final long serialVersionUID = 1L;

/**

* @see HttpServlet#HttpServlet()

*/

public GetComputerCode() {

super();

}

public void init() throws ServletException {

super.init();

System.out.println("..................这样在web容器启动的时候,就会执行这句话了!");

}

/**

* @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());

}

/**

* @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);

}

}

2,在项目的WebRoot/WEB-INF/web.xml 中,添加

<servlet>

<servlet-name>GetComputerCode</servlet-name>

<servlet-class>com.pinao.dao.GetComputerCode</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

下面是我的测试的xml文件

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

<display-name>JudgeDeadTime</display-name>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

<welcome-file>index.htm</welcome-file>

<welcome-file>index.jsp</welcome-file>

<welcome-file>default.html</welcome-file>

<welcome-file>default.htm</welcome-file>

<welcome-file>default.jsp</welcome-file>

</welcome-file-list>

<servlet>

<servlet-name>GetComputerCode</servlet-name>

<servlet-class>com.pinao.dao.GetComputerCode</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

</web-app>

3,运行Tomcat,发现在Servlet中的Static中的打印“YYYYYYYYYYYYYYYY”和Init中的方法都执行了

(0)

相关推荐