发新话题
打印

tomcat中如何自动运行程序代码

tomcat中如何自动运行程序代码

首先这些东西初始的时候是都不会的, 所以就要学习么!
我这个想法的初始原因,就是想自动的载入hibernateSessionFactory,要不然每次启动hibernate的时候, 兄弟们表示测试起来狠不爽;所以决心将‘启动’提前。

在类中,可以定义static代码,当类被首次加载时,自动执行其中的代码。例如:

public class Test
{
static
{
//类被加载时执行的代码
}

public Test()
{
}

...
//其他方法
}

在java中,当使用到一个类的时候,该类才会被加载到内存中。因此,如果上面的类Test没有被调用,那么其static部分的代码也不会被执行。

为了让程序代码在tomcat启动时自动运行,需要写一个servlet,在tomcat的web.xml中配置后,可以随tomcat启动而自动运行。在WEB-INFO/web.xml中,配置如下:

关键是<servlet>与</servlet>之间的参数:<load-on-startup>。加了这个 参数后,tomcat启动时,会自动加载类com.ee2ee.servlet.TestAutoRun。在servlet类的init方法中放置需要自 动执行的代码即可。


实例代码:
package com.ee2ee.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class TestAutoRun extends HttpServlet
{
    private HttpServletRequest request;
    private PrintWriter out;

    //当servlet类被加载时,执行本函数
    //在本方法中放置代码即可完成自动加载
    public void init(ServletConfig config) throws ServletException
    {
        super.init(config);
   
    //此处放置需要自动执行的代码
        System.out.println("I 'm ok now.");
    }

    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //以下是标准的GET方法处理,由http的GET方法触发(调用)
        this.doPost(request, response);
    }

    //Process the HTTP Post request
    //标准的POST方法处理,由http的POST方法触发(调用)
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {   
        response.setContentType("text/html; charset=GB2312");
        PrintWriter out = response.getWriter();

        this.request = request;
        this.out = out;

        out.println("<html>");
        out.println("<head>");
        out.println("</head>");
        out.println("<body>");
        out.println("this is a test.<br>");
        out.println("</body>");
        out.println("</html>");
    }

    //Clean up resources
    public void destroy()
    {

    }
}


TOP

TOP

发新话题

CnLabs |Tools |Videos |Domain |Host | Site | Movie | Down | 分类 | 外贸 | RSS | Manual | 工具 | 传文件 | 传图片 | 易图网 | 支付页