溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在Spring mvc中防止數(shù)據(jù)重復(fù)提交

發(fā)布時(shí)間:2021-05-21 16:12:24 來源:億速云 閱讀:178 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關(guān)怎么在Spring mvc中防止數(shù)據(jù)重復(fù)提交,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

分析:

這里使用的防止數(shù)據(jù)重復(fù)提交的方法是使用token,給所有的url加一個(gè)攔截器,在攔截器里面用java的UUID生成一個(gè)隨機(jī)的UUID并把這個(gè)UUID放到session里面,然后在瀏覽器做數(shù)據(jù)提交的時(shí)候?qū)⒋薝UID提交到服務(wù)器。服務(wù)器在接收到此UUID后,檢查一下該UUID是否已經(jīng)被提交,如果已經(jīng)被提交,則不讓邏輯繼續(xù)執(zhí)行下去。

源碼實(shí)現(xiàn):

注解Token代碼:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Token {
  boolean save() default false;
  boolean remove() default false;
}

攔截器TokenInterceptor代碼:

public class TokenInterceptor 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();
      Token annotation = method.getAnnotation(Token.class);
      if (annotation != null) {
        boolean needSaveSession = annotation.save();
        if (needSaveSession) {
          request.getSession(false).setAttribute("token", UUID.randomUUID().toString());
        }
        boolean needRemoveSession = annotation.remove();
        if (needRemoveSession) {
          if (isRepeatSubmit(request)) {
            return false;
          }
          request.getSession(false).removeAttribute("token");
        }
      }
      return true;
    } else {
      return super.preHandle(request, response, handler);
    }
  }

  private boolean isRepeatSubmit(HttpServletRequest request) {
    String serverToken = (String) request.getSession(false).getAttribute("token");
    if (serverToken == null) {
      return true;
    }
    String clinetToken = request.getParameter("token");
    if (clinetToken == null) {
      return true;
    }
    if (!serverToken.equals(clinetToken)) {
      return true;
    }
    return false;
  }
}

Spring MVC的配置文件:

<!-- 攔截器配置 -->
  <mvc:interceptors>
    <!-- 配置Token攔截器,防止用戶重復(fù)提交數(shù)據(jù) -->
    <mvc:interceptor>
      <mvc:mapping path="/**"/>
      <bean class="com.storezhang.web.spring.TokenInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

使用方法:

1、在需要生成token的controller上增加@Token(save=true);
2、而在需要檢查重復(fù)提交的controller上添加@Token(remove=true)就可以了。

另外,你需要在view里在form里增加下面代碼:

<input type="hidden" name="token" value="${token}" />

看完上述內(nèi)容,你們對怎么在Spring mvc中防止數(shù)據(jù)重復(fù)提交有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI