JSP application 对象的使用

项目的数据库有时候要从外部来检查是不是连接OK,常常从检查的客户端会每隔一段时间来发送请求,客户端那边发送请求的频率我们自己是不可以配置的,但是我们可以用代码来控制:

Connection conn = null;
	Session dbSession = null;
	PreparedStatement psts = null;
	ResultSet rs = null;
	//set the time gip to excute the code to connect to DB
	long distanceConfig = 3*60*1000;
	try {	
		Date nowTime = new Date();
		Date lastTime = (Date)application.getAttribute("lastTime");
		if(lastTime == null){
			lastTime = nowTime;
		}
		long distance = nowTime.getTime() - lastTime.getTime();
		if(distance >= distanceConfig || distance == 0){
			dbSession = com.hgc.bkrm.util.HibernateUtil.currentSession();
			conn = dbSession.connection();
			psts = conn.prepareStatement("select 1 from dual");
			rs = psts.executeQuery();
                        application.setAttribute("lastTime", nowTime);
			out.println("95bookingportal_This aims EC");
			out.println("--------------check the DB,excute the DB connection code,it is normal");
		} else{
			out.println("95bookingportal_This aims EC");
			out.println("------------------do not excute the DB connetion code,you can try it 3 minute later!");
			
		}
	} catch (Exception e) {
		out.println("ERROR:"+e.getMessage());
		e.printStackTrace();		
	}

 后面关闭的代码省略。其中

application.setAttribute("lastTime", nowTime);

是要用application来保存time,这样才是全局的保存方法。记录上次访问的时间。

另外,该例子中的

psts = conn.prepareStatement("select 1 from dual");

sql语句经常用来检查数据库的正确性。dual是oracle数据库中的一个虚拟表,当然你也可以写成select 2(或者其他都可以)from dual。就看你自己喜欢了,你写了什么就会返回什么。

posted @ 2013-08-07 18:26  yuer629  阅读(130)  评论(0编辑  收藏  举报