打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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中的方法都执行了

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
jsp+servlet实现注册登录,不用数据库
springboot项目,servlet实现一个转盘抽奖程序
javaweb文件下载功能实现
Java
Java压缩技术(五) GZIP相关——浏览器解析
javaweb学习之Servlet
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服