📄 applicationlistener.java
字号:
package cn.ialvin.bbs.listener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.regex.Matcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import cn.ialvin.bbs.dao.DAOFactory;
import cn.ialvin.sql.ConnectionPool;
import cn.ialvin.sql.DBConfig;
import cn.ialvin.util.MatcheProcesser;
import cn.ialvin.util.RegExp;
public class ApplicationListener implements ServletContextListener, MatcheProcesser {
public void contextDestroyed(ServletContextEvent e) {
if (ApplicationListener.pool != null) {
ApplicationListener.pool.close();
}
}
ServletContext application = null;
private static ConnectionPool pool = null;
private boolean initDBConfig() {
String config_xml_path = this.application.getRealPath("/WEB-INF/coxn.xml");
File file = new File(config_xml_path);
if (!file.exists() && !file.isFile())
return false;
if (!file.canRead())
return false;
SAXBuilder sb = new SAXBuilder();
Document doc = null;
try {
doc = sb.build(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (doc == null) {
return false;
}
Element root = doc.getRootElement();
DBConfig config = new DBConfig();
config.setDBType(root.getChild("DBType").getText());
config.setDriver(root.getChild("driver").getText());
config.setUID(root.getChild("uid").getText());
config.setPWD(root.getChild("pwd").getText());
config.setMax(Integer.parseInt(root.getChild("max").getText()));
config.setMin(Integer.parseInt(root.getChild("min").getText()));
config.setUrl(root.getChild("dburl").getText().trim());
config.setUrl(
new RegExp("\\<\\[([^\\]]+)\\]\\>", "g")
.replace(config.getUrl(), this)
);
try {
ConnectionPool pool = ConnectionPool.newInstance(config);
DAOFactory factory = new DAOFactory(pool);
boolean flag = factory.testDBType();
factory.destroy();
if (!flag) return false;
this.application.setAttribute("DBPool", pool);
ApplicationListener.pool = pool;
} catch (SQLException e) {
e.printStackTrace();
return false;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return false;
}
return true;
}
public String doProcess(Matcher m) {
return application.getRealPath(m.group(1));
}
public void contextInitialized(ServletContextEvent e) {
this.application = e.getServletContext();
try {
if (this.initDBConfig())
this.application.setAttribute("DB_CONNECTION_INITED", "YES");
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -