Bootstrap

java表单token_form 表单提交,防止重复提交,加token

大体步骤分为:

1.通过java 生成随机数放在http 的header 里面

String token = IdentityUtil.uuid32();

getRequest().getSession().setAttribute("server_token", token);

2.把生成token 放到隐藏域中,

String html = "";

try {

ctx.byteWriter.writeString(html);

} catch (IOException e) {

e.printStackTrace();

}

输出到页面;

3.写个拦截器,页面传过来的token与java生成token进行匹配;

public void intercept(DispatcherExecutor executor) {

String server_token = PuffContext.removeSessionAttr("server_token");

String client_token = PuffContext.getRequest().getHeader("Puff-ClientToken");

if (StringUtil.empty(server_token) || StringUtil.empty(client_token) || !server_token.equals(client_token)) {

if (PuffContext.ajax()) {

RetMsg msg = RetMsg.error(RetCode.ILLEGAL_SUBMIT, "非法表单提交申请!");

PuffContext.getResponse().setHeader("illegal_submit", "yes");

executor.setResult(ViewFactory.json(msg));

} else {

throw new IllegalArgumentException("非法表单提交申请!");

}

} else {

executor.execute();

}

//如果匹配了。重新生成token到页面,防止重复提交

String token = IdentityUtil.uuid32();

PuffContext.setSessionAttribute("server_token", token);

PuffContext.getResponse().setHeader("server_token", token);

}

4.页面

$.ajax({

url:"${ctxPath}/xx",

data:$(‘#form‘).serialize(),

type:"POST",

datatype:"json",

beforeSend: function(request) {

//把token 放到http header 中

request.setRequestHeader("Puff-ClientToken",$("#puff_beetl_client_token").val());

},

success:function(data){

if(data.code=="403"){

layer.close(index);

Popbox.sureWithBtn(data.msg);

}else{

var msg=eval("("+data.msg+")");

var code=msg.code;

if(code==success){

layer.close(index);

window.location.href="${ctxPath}/success;

}else{

flag=false;

layer.close(index);

Popbox.sureWithBtn(msg.message);

}

}

},

complete:function(request){

if(!flag){  //提交成功,就不改变http头部header,就是当失败才重新把token放到http header中

$("#puff_beetl_client_token").val(request.getResponseHeader("server_token"));

}

},

error:function(){

layer.close(index);

}});

;