---
title: "清空session 相关方法和GUID 的正则验证"
author: "hb_keepmoving"
date: "2013-02-27T10:31:38Z"
tags: []
categories: ["编程语言"]
slug: "session-guid"
draft: false
lastmod: "2013-03-28T09:55:53Z"
id: 1815758
url: "https://hb-keepmoving.iteye.com/blog/1815758"
---

1.session 自动失效的时候 更新数据。

解决方法：写一个类 实现HttpSessionListener（只有2个类），再根据需求，重写一下方法。

      方法一、sessionCreated （作用于session 创建的时候）

      方法二、sessionDestroyed（作用于session 失效的时候）

 

2.限制权限，可以在StateMachine.xml 文件中加 &lt;Access&gt;标签。

 

3.关闭浏览器（刷新和关闭），update数据库-清空已保存的session

解决方案：

1.在&lt;body&gt;加onbeforeunload事件(最好不用onunload)，onkeydown事件 是监听F5-刷新的。

**备注：**Onbeforeunload是正要去服务器读 取新的页面时调用，此时还没开始读取；而onunload则已经从服务器上读到了需要加载的新的页面，在即将替换掉当前页面时调用。Onunload是无 法阻止页面的更新和关闭的。而 Onbeforeunload 可以做到。

 

2.在**invalidate()**方法中，可以模仿 form提交，则server端收到请求后，就可以做想做的事情了。

 

**&lt;body  onkeydown="keyDwonEvent(event)" onbeforeunload="invalidate()"&gt;**

js文件中：

```
var clickF5=false;
var clickRefresh=false;
var clickAltF4=false;
var clickTaskBarClose=false;

function keyDwonEvent(e) {
	var currKey=0,e=e||event;
    currKey=e.keyCode||e.which||e.charCode;
    clickF5 = (currKey==116);
    if(currKey==115&&e.altKey){
		clickAltF4=true;
	} else {
		clickAltF4=false;
	}
};

document.onmouseout = function() {
	clickTaskBarClose=true;
};

document.onclick = function() {
	 clickRefresh=false;
	 clickTaskBarClose=false;
	 clickAltF4=false;
};

document.oncontextmenu=function() {
	 clickRefresh=true;
};

document.onmousemove=function(){
	clickTaskBarClose=false;
};

function invalidate(){
	if ((!clickF5&&!clickRefresh)&&(clickAltF4||clickTaskBarClose)) {
    	document.forms[0].action = "xxxxxxxx";
    	document.forms[0].method = 'post';
    	document.forms[0].submit();
	 }
}
```

 

4.验证GUID 的正则表达式

```
//check filename ,it must like guid format
	    		//validation GUID (8-4-4-4-12)
	    		String regx = "^[A-Za-z0-9]{8}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{4}-[A-Za-z0-9]{12}$";
	    		Pattern pattern = Pattern.compile(regx);
	    		if (null == sFileName || "".equalsIgnoreCase(sFileName)) {
					return;
				}
	    		Matcher mat = pattern.matcher(sFileName);
	    		if (!mat.find()) {
					//invalid
	    			ServletOutputStream out = response.getOutputStream();
	    			String content = "File name["+sFileName+"] is invalid.";
	    			out.write(content.getBytes());
	    			out.flush();
	    			out.close();
	    			return;
				}
```