springmvc 防止表單重復(fù)提交的兩種方法
最近在本地開發(fā)測試的時候,遇到一個表單重復(fù)提交的現(xiàn)象。 因為網(wǎng)絡(luò)延遲的問題,我點擊了兩次提交按鈕,數(shù)據(jù)庫里生成了兩條記錄。其實這種現(xiàn)象以前也有遇到過,一般都是提交后把按鈕置灰,無法再次提交,這是很常見的客戶端處理的方式。 但是這不是從根本上解決問題,雖然客戶端解決了多次提交的問題,但是接口中依舊存在著問題。假設(shè)我們不是從客戶端提交,而是被其他的系統(tǒng)調(diào)用,當(dāng)遇到網(wǎng)絡(luò)延遲,系統(tǒng)補償?shù)臅r候,還會遇到這種問題
1、通過session中的token驗證
- 初始化頁面時生成一個唯一token,將其放在頁面隱藏域和session中
- 攔截器攔截請求,校驗來自頁面請求中的token與session中的token是否一致
- 判斷,如果一致則提交成功并移除session中的token,不一致則說明重復(fù)提交并記錄日志
步驟1:創(chuàng)建自定義注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Token {
boolean save() default false;
boolean remove() default false;
}
步驟2:創(chuàng)建自定義攔截器(@slf4j是lombok的注解)
@Slf4j
public class RepeatSubmitInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HandlerMethod handlerMethod = null;
try {
handlerMethod = (HandlerMethod)handler;
} catch (Exception e) {
return true;
}
Method method = handlerMethod.getMethod();
Token token = method.getAnnotation(Token.class);
if(token != null ){
boolean saveSession = token.save();
if(saveSession){
request.getSession(true).setAttribute("token", UUID.randomUUID());
}
boolean removeSession = token.remove();
if(removeSession){
if(isRepeatSubmitSession(request)){
log.info("repeat submit session :" + request.getServletPath());
response.sendRedirect("/error/409");
return false;
}
request.getSession(true).removeAttribute("token");
}
}
return true;
}
private boolean isRepeatSubmitSession(HttpServletRequest request){
String sessionToken = String.valueOf(request.getSession(true).getAttribute("token") == null ? "" : request.getSession(true).getAttribute("token"));
String clientToken = String.valueOf(request.getParameter("token") == null ? "" : request.getParameter("token"));
if(sessionToken == null || sessionToken.equals("")){
return true;
}
if(clientToken == null || clientToken.equals("")){
return true;
}
if(!sessionToken.equals(clientToken)){
return true;
}
return false;
}
}
步驟3:將自定義攔截器添加到配置文件
<mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.chinagdn.base.common.interceptor.RepeatSubmitInterceptor"/> </mvc:interceptor>
使用案例
//save = true 用于生成token
@Token(save = true)
@RequestMapping(value = "save", method = RequestMethod.GET)
public String save(LoginUser loginUser, Model model) throws Exception {
return "sys/user/edit";
}
//remove = true 用于驗證token
@Token(remove = true)
@RequestMapping(value = "save", method = RequestMethod.POST)
public String save(@Valid LoginUser loginUser, Errors errors, RedirectAttributes redirectAttributes, Model model) throws Exception {
//.....
}
jsp頁面隱藏域添加token
<input type="hidden" name="token" value="${sessionScope.token}">
2、通過當(dāng)前用戶上一次請求的url和參數(shù)驗證重復(fù)提交
攔截器攔截請求,將上一次請求的url和參數(shù)和這次的對比
判斷,是否一致說明重復(fù)提交并記錄日志
步驟1:創(chuàng)建自定義注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SameUrlData {
}
步驟2:創(chuàng)建自定義攔截器
public class SameUrlDataInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
//是否有 SameUrlData 注解
SameUrlData annotation = method.getAnnotation(SameUrlData.class);
if (annotation != null) {
if (repeatDataValidator(request)) {//如果重復(fù)相同數(shù)據(jù)
response.sendRedirect("/error/409");
return false;
} else {
return true;
}
}
return true;
} else {
return super.preHandle(request, response, handler);
}
}
/**
* 驗證同一個url數(shù)據(jù)是否相同提交 ,相同返回true
* @param httpServletRequest
* @return
*/
private boolean repeatDataValidator(HttpServletRequest httpServletRequest) {
String params = JsonMapper.toJsonString(httpServletRequest.getParameterMap());
String url = httpServletRequest.getRequestURI();
Map<String, String> map = new HashMap<>();
map.put(url, params);
String nowUrlParams = map.toString();//
Object preUrlParams = httpServletRequest.getSession().getAttribute("repeatData");
if (preUrlParams == null) { //如果上一個數(shù)據(jù)為null,表示還沒有訪問頁面
httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams);
return false;
} else { //否則,已經(jīng)訪問過頁面
if (preUrlParams.toString().equals(nowUrlParams)) { //如果上次url+數(shù)據(jù)和本次url+數(shù)據(jù)相同,則表示城府添加數(shù)據(jù)
return true;
} else { //如果上次 url+數(shù)據(jù) 和本次url加數(shù)據(jù)不同,則不是重復(fù)提交
httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams);
return false;
}
}
}
}
步驟3:將自定義攔截器添加到配置文件
<mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.chinagdn.base.common.interceptor.SameUrlDataInterceptor"/> </mvc:interceptor>
使用案例
//在controller層使用 @SameUrlData 注解即可
@SameUrlData
@RequestMapping(value = "save", method = RequestMethod.POST)
public String save(@Valid LoginUser loginUser, Errors errors, RedirectAttributes redirectAttributes, Model model) throws Exception {
//.....
}
到此這篇關(guān)于springmvc 防止表單重復(fù)提交的兩種方法的文章就介紹到這了,更多相關(guān)springmvc 防止表單重復(fù)提交內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot公共字段填充及ThreadLocal模塊改進方案
這篇文章主要為大家介紹了Springboot公共字段填充及ThreadLocal模塊改進方案詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11
基于Freemarker和xml實現(xiàn)Java導(dǎo)出word
這篇文章主要介紹了基于Freemarker和xml實現(xiàn)Java導(dǎo)出word,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04

