synchronized 用法,实例讲解
package com.asiainfolinkage.ems.web.controller.base; import java.math.BigInteger; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * 附带token的控制器 * @version 1.0 Copyright 2013年7月29日 下午3:38:30 */ public abstract class TokenBaseController extends BaseController { private static Map<String, String> springmvc_token = new HashMap<String, String>(); /** 生成一个唯一值的token */ public String generateGUID(HttpSession session) { String token = ""; Date date = new Date(); synchronized (springmvc_token) { try { Object obj = session.getAttribute(Constants.SPRING_MVC_TOKENNAME); if (obj != null) springmvc_token = (Map<String, String>) session.getAttribute(Constants.SPRING_MVC_TOKENNAME); token = new BigInteger(165, new Random()).toString(36).toUpperCase(); springmvc_token.put(Constants.DEFAULT_TOKEN_NAME + "." + token, token); session.setAttribute(Constants.SPRING_MVC_TOKENNAME, springmvc_token); Constants.TOKEN_VALUE = token; } catch (IllegalStateException e) { _log.error("generateGUID() mothod find bug,by token session..."); } } return token; } /** 验证表单token值和session中的token值是否一致 */ public boolean validToken(HttpServletRequest request) { String inputToken = getInputToken(request); if (inputToken == null) { _log.warn("token is not valid!inputToken is NULL"); return false; } HttpSession session = request.getSession(); Map<String, String> tokenMap = (Map<String, String>) session.getAttribute(Constants.SPRING_MVC_TOKENNAME); if (tokenMap == null || tokenMap.size() < 1) { _log.warn("token is not valid!sessionToken is NULL"); return false; } String sessionToken = tokenMap.get(Constants.DEFAULT_TOKEN_NAME + "." + inputToken); if (!inputToken.equals(sessionToken)) { _log.warn("token is not valid!inputToken='" + inputToken + "',sessionToken = '" + sessionToken + "'"); return false; } tokenMap.remove(Constants.DEFAULT_TOKEN_NAME + "." + inputToken); session.setAttribute(Constants.SPRING_MVC_TOKENNAME, tokenMap); return true; } /** 获取表单中token值 */ private String getInputToken(HttpServletRequest request) { Map params = request.getParameterMap(); if (!params.containsKey(Constants.DEFAULT_TOKEN_NAME)) { _log.warn("Could not find token name in params."); return null; } String[] tokens = (String[]) (String[]) params.get(Constants.DEFAULT_TOKEN_NAME); if ((tokens == null) || (tokens.length < 1)) { _log.warn("Got a null or empty token name."); return null; } return tokens[0]; } }
补充:软件开发 , Java ,