jsp 防止表单多次提交
1:首先java 后台代码生成一个token,然后保存到jsp 页面的一个隐藏控件并且保存到set session中
*/ @RequestMapping("/yuDengJi") public String registrationAdd(HttpSession session, HttpServletResponse response, Model model, HttpServletRequest request,String exhiId,String canGuanId,String ispay,String type,String hangYe) { YuDengJi rsEx = new YuDengJi(); rsEx.setExhiId(exhiId);//展览ID rsEx.setType(type);//类型(0参展团1参观团,2标准展位,3门票) model.addAttribute("exhiId", exhiId);//展馆ID model.addAttribute("canGuanId",canGuanId);//参观ID model.addAttribute("ispay",ispay);//参观团详细页面意向登记只显示参观 model.addAttribute("hangYe", hangYe);//行业id model.addAttribute("tyep", type);//类型(0参展团1参观团,2标准展位,3门票) model.addAttribute("countYuDengJi", yuDengJiService.getCountYuDengJi(rsEx));//已经登记的参展或参观的个数 String token = UUID.randomUUID().toString();//生成token 然后保存到jsp 页面的隐藏控件 session.setAttribute("yudengjiToken", token); model.addAttribute("token", token); return "modules/yudengji/addYuDengJi"; }
2:当用户提交表单时到后台Controller 类保存方法进行判断,当token 等于null 时 或者 隐藏控件的token 值 不等于session 的token 值就判断操作为多次提交表单
@ResponseBody @RequestMapping("/yuDengJi/saveExhibitors") public String saveRegistration(HttpSession session, HttpServletResponse response, Model model, HttpServletRequest request,String type,String hangYe,String token) { YuDengJi rsEx = new YuDengJi(); rsEx.setCompanyName(request.getParameter("companyName").trim());// 公司名称 rsEx.setType(type);// 类型 rsEx.setCanZhanMianJi(Double.parseDouble(request.getParameter("canZhanMianJi").trim()));// 意向参展面积 rsEx.setCanZhanYuSuan(Double.parseDouble(request.getParameter("canZhanYuSuan").trim()));//参展预算 rsEx.setName(request.getParameter("name").trim());// 联系人姓名 rsEx.setPhone(request.getParameter("phone").trim());// 联系人手机号码 rsEx.setMail(request.getParameter("mail").trim());// 邮箱 rsEx.setKaoChaDi(request.getParameter("kaoChaDi").trim());// 意向考察目的地 String exhiId = request.getParameter("exhiId").trim(); rsEx.setExhiId(exhiId);//展览ID rsEx.setHangYe(hangYe);//关联行业 Account account = (Account)session.getAttribute(Constants.ACCOUNT); String accountId = account.getId(); if(!"".equals(accountId) && accountId !=null){//用户ID rsEx.setAccountId(Integer.parseInt(accountId)); } try { String yudengjiToken = (String)session.getAttribute("yudengjiToken"); if(yudengjiToken == null || !yudengjiToken.equals(token)){ }else{ yuDengJiService.save(rsEx); session.removeAttribute("yudengjiToken"); } return "ok"; /*String ulr = "redirect:" + frontPath + "/exhi/product-"+exhiId+urlSuffix; System.out.println("ulr>>>>"+ulr); return "redirect:" + frontPath + "/exhi/product-"+exhiId+urlSuffix;*/ } catch (Exception e) { e.printStackTrace(); return "no"; } }
3:用完后记得从session 中 remove 掉token
session.removeAttribute("yudengjiToken");