JSP刷新页面表单重复提交问题解决办法分享
使用sessionid和时间戳作为标识,关键代码如下:
public class sswpdjaction extends baseaction{
public string execute(){
/**业务代码**/
................
//设置标识
this.setsessiontoken();
//转到添加页面
return "toadd";
}
public string resave(){
if(this.token != null && this.token.equals(this.getsessiontoken())){
/**设置新标识**/
this.setsessiontoken();
/**业务代码**/
..............
return "toadd";
}else{
printwriter out = null;
try{
httpservletresponse.setcontenttype("text/html;charset=utf-8");
out = httpservletresponse.getwriter();
out.println("<script>alert('刷新提交表单!');</script>");
out.flush();
}catch(ioexception e){
e.printstacktrace();
}finally{
if(out != null){
out.close();
}
}
}
return null;
}
}
public class baseaction extends actionsupport{
/**jsp页面标识**/
protected string token;
public string gettoken(){
return token;
}
public void settoken(string token){
this.token = token;
}
public string getsessiontoken(){
if(null != httpsession.getattribute("token")){
return httpsession.getattribute("token");
}else{
return null;
}
}
/**标识生成**/
public void setsessiontoken(){
string flag = usemd5(httpsession.getid() + system.currenttimemillis());
httpsession.setattribute("token", flag);
httpservletrequest.setattribute("sessiontoken", flag);
}
/**md5加密**/
private string usemd5(string str){
byte[] bs = str.getbytes();
string result = null;
try{
messagedigest md5 = messagedigest.getinstance("md5");
md5.update(bs);
result = md5.digest().tostring();
}catch(nosuchalgorithmexception e){
e.printstacktrace();
}finally{
}
return result;
}
}
jsp页面设置标识隐藏域:
<form>
<input type="hidden" name="token" value="${sessiontoken}" />
</form>