JavaWeb 服务启动时,在后台启动加载一个类

两种方法,

一、监听(Listener)

1、创建个监听类,继承ServletContextListener

package tbp.common.xkins;
import javax.servlet.ServletContextEvent;
import net.sf.opentranquera.xkins.core.Skin;
import net.sf.opentranquera.xkins.core.loaders.XkinsLoaderServletContextListener;
import org.apache.commons.lang.StringUtils;
public class XkinsLoaderListenerCustom extends XkinsLoaderServletContextListener {
public void contextInitialized(ServletContextEvent context) {
// Normal XKINS stuffs
super.contextInitialized(context);
String defaultSkin = context.getServletContext().getInitParameter("xkins.defaultSkin");
if (StringUtils.isEmpty(defaultSkin))
defaultSkin = "default";
context.getServletContext().setAttribute(Skin.ATTR_DEFAULT_SKIN_NAME, defaultSkin);
}
}

2、在web.xml中配置,listener类可在web启动时自动加载.



tbp.common.xkins.XkinsLoaderListenerCustom

二、配置随项目启动而启动的Servlet

1、创建一个类继承HttpServlet,再web.xml配置文件中配置servlet信息

package tbp.component.workflow.service.interf.impl;
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import tbp.component.workflow.service.interf.RegisterRmi;
public class ExternalInterfaceRmiRegisterServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
    try {
RegisterRmi.startRmi();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}

2、在web.xml配置一个servlet设置启动顺序优先级高些(即:web服务启动时调用这个类)

  
ExternalInterfaceRmiRegisterServlet  
tbp.component.workflow.service.interf.impl.ExternalInterfaceRmiRegisterServlet  
 
1 
 

你可能感兴趣的:(JavaWeb 服务启动时,在后台启动加载一个类)