packagecom.taiji.waf.filter;importjava.net.InetAddress;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.SQLException;importjavax.servlet.ServletContextAttributeEvent;importjavax.servlet.ServletContextAttributeListener;importjavax.servlet.ServletContextEvent;importjavax.servlet.ServletContextListener;importcom.taiji.waf.WAFConfigure;/*** ServletContext对象监听器.
* 作用:监听ServletContext对象生命周期及ServletContext对象中属性变化情况
**/
public class ContextListener implementsServletContextListener,
ServletContextAttributeListener {/*** 当应用关闭时将执行此方法*/
public voidcontextDestroyed(ServletContextEvent arg0) {
System.out.println("【监听到】应用被关闭!");
closeDataConn();
}/*** 当应用启动时将执行此方法*/
public voidcontextInitialized(ServletContextEvent arg0) {
System.out.println("【监听到】应用被启动!");
}/*** 当ServletContext对象中新增属性时将执行此方法*/
public voidattributeAdded(ServletContextAttributeEvent arg0) {
System.out.println("【监听到】ServletContext对象中新增一名为" +arg0.getName()+ "的属性,其属性值为:" +arg0.getValue());
}/*** 当ServletContext对象中删除属性时将执行此方法*/
public voidattributeRemoved(ServletContextAttributeEvent arg0) {
System.out.println("【监听到】ServletContext对象中一名为" +arg0.getName()+ "的属性被删除!");
}/*** 当ServletContext对象中更新属性时将执行此方法*/
public voidattributeReplaced(ServletContextAttributeEvent arg0) {
System.out.println("【监听到】ServletContext对象中一名为" +arg0.getName()+ "的属性被更新!");
}/*** 获得计算机名称
*@return
*/
public staticString getHostName(){
String hostName="";try{
InetAddress addr=InetAddress.getLocalHost();
hostName=addr.getHostName().toString(); //获取本机计算机名称
}catch(Exception e){
e.printStackTrace();
}returnhostName;
}/*** 关闭所有数据库连接*/
private static voidcloseDataConn() {
String name=getHostName();
String sql=closeDataConn(name);
String driverClass= WAFConfigure.getProperty("Broker_driver");
String url= WAFConfigure.getProperty("Broker_url");
String user= WAFConfigure.getProperty("Broker_username");
String password= WAFConfigure.getProperty("Broker_password");
Connection conn=null;try{
Class.forName(driverClass);
conn=DriverManager.getConnection(url,user,password);
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.executeUpdate();
pstmt.close();
}catch(Exception e) {
e.printStackTrace();
}finally{try{
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}/*** 拼写关闭所有当前用户建立的数据库联接SQL
*@paramownuserId*/
public staticString closeDataConn(String ownuserId){
String sql=" declare cursor cur_sess is select sid, serial# from v$session where status = 'INACTIVE'";
sql+=" and type != 'BACKGROUD' and (machine=? or machine='localhost'); w_sid number; w_serial number; begin open cur_sess; loop fetch cur_sess into w_sid,w_serial; if cur_sess%notfound then exit; end if;";
sql+=" execute immediate 'alter system kill session '''||w_sid||','||w_serial||''''; end loop; end;";returnsql;
}
}