基於接口開發的令牌

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Token {

	/** 是否要將TOKEN值保存在session中 */
	boolean save() default false;

	/** 是否刪除session中保存的TOKEN值 */
	boolean remove() default false;
}

方法上加上註解

@Token(save=true)
public void methoda(){
     ...
}

@Token(remove=true)
public void methodb(){
    ...
}


攔截器設置令牌

            // 取得方法的TOKEN註解
            Token annotation = method.getAnnotation(Token.class);
            if (annotation != null) {

                // 先驗證,再保存(爲了在同一個方法中進行保存/驗證操作)
                if (annotation.remove()) {
                    if (isRepeatSubmit(request)) {
                        throw new SysException("TOKEN驗證失敗,請保存後,再進行TOKEN的驗證。");
                    }
                    request.getSession(false).removeAttribute(TOKEN_KEY_NAME);
                }

                // TOKEN的保存
                if (annotation.save()) {
                    request.getSession(false).setAttribute(TOKEN_KEY_NAME, UUID.randomUUID().toString());
                }
            }

    /**
     * 驗證是否爲重複提交內容。
     * 
     * @param request Request對象
     * @return true:重複提交; flase:不是重複提交
     * @exception Exception 異常
     */
    private boolean isRepeatSubmit(HttpServletRequest request) {
        String serverToken = (String) request.getSession(false).getAttribute(TOKEN_KEY_NAME);
        if (serverToken == null) {
            return true;
        }
        String clinetToken = request.getParameter(TOKEN_KEY_NAME);
        if (clinetToken == null) {
            return true;
        }
        if (!serverToken.equals(clinetToken)) {
            return true;
        }
        return false;
    }





發佈了37 篇原創文章 · 獲贊 16 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章