// 判斷是否同個域名 public static boolean validate(HttpServletRequest request) { String Referer = ""; boolean referer_sign = true; // true 站內提交,驗證經過 //false 站外提交,驗證失敗 Enumeration headerValues = request.getHeaders("Referer"); while (headerValues.hasMoreElements()) Referer = (String) headerValues.nextElement(); // 判斷是否存在請求頁面 if (Referer == null || Referer.length() < 1) referer_sign = false; else { // 判斷請求頁面和getRequestURI是否相同 String servername_str = request.getServerName(); if (servername_str != null || servername_str.length() > 0) { int index = 0; if (Referer.indexOf("https://") == 0) { index = 8; } else if (Referer.indexOf("http://") == 0) { index = 7; } if (Referer.length() - index < servername_str.length()) // 長度不夠 referer_sign = false; else { // 比較字符串(主機名稱)是否相同 String referer_str = Referer.substring(index, index + servername_str.length()); if (!servername_str.equalsIgnoreCase(referer_str)) referer_sign = false; } } else referer_sign = false; } return referer_sign; }