這篇文章主要介紹了jsp防止跨域提交數據的具體實現,需要的朋友可以參考下
代碼如下: //ArgsIsValidFilter .java過濾器代碼清單: package com.hety.uitl; import java.io.IOException; import java.util.Enumeration; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class ArgsIsValidFilter implements Filter { private static Log log = LogFactory.getLog(ArgsIsValidFilter.class); public void destroy() { } @SuppressWarnings("unchecked") public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) arg0; HttpServletResponse response = (HttpServletResponse) arg1; String servername_str = request.getServerName(); String currentURI = request.getRequestURI(); Enumeration headerValues = request.getHeaders("Referer"); String tmpHeaderValue = ""; boolean isValid = true; //指定需要跳過攔截的頁面地址,如果需要新增,可直接在數組中添加。 //“建議” String [] ignoreURIS={"/back/", "/Info.jsp", "/pzxx.jsp" }; while (headerValues.hasMoreElements()) { // 得到完整的路徑:如“http://www.domain.com.cn:8023/front/zwgk/zwgk.jsp?id=1283” tmpHeaderValue = (String) headerValues.nextElement(); } if(log.isInfoEnabled()){ log.info(" 獲得的參數url為: " + tmpHeaderValue ); log.info(" 系統取得的url為:"+ currentURI); } if ("".equals(tmpHeaderValue)) { isValid = false; if(log.isInfoEnabled()){ log.info(" 獲得的參數url為: empty"); log.info(" 系統取得的url為:"+ currentURI); log.info("系統提示:請求可能來自外域!"); } } else { if(log.isInfoEnabled()){ log.info("獲得的參數長度為:"+tmpHeaderValue.length()); } tmpHeaderValue = tmpHeaderValue.toLowerCase(); servername_str = servername_str.toLowerCase(); int len = 0; if (tmpHeaderValue.startsWith("https://")) { len = 8; } else if (tmpHeaderValue.startsWith("http://")) { len = 7; } if(log.isInfoEnabled()){ log.info("截取前的字符串為:" + tmpHeaderValue ); log.info( "從第 " + len + " 位開始截取,截取長度為:" + servername_str.length()); } String tmp = tmpHeaderValue.substring(len, servername_str.length() + len); if(log.isInfoEnabled()){ log.info("截取後的字符串為:" + tmp); } if (tmp.length() < servername_str.length()) { // 長度不夠 isValid = false; if(log.isInfoEnabled()){ log.info("截取後的字符串長度不夠,請求可能來自外域!"); } } else if (!tmp.equals(servername_str)) {// 比較字符串(主機名稱)是否相同 isValid = false; if(log.isInfoEnabled()){ log.info("域名匹配失敗,請求來自外域!"); } } } // 跳過指定需要攔截的頁面地址 for (String ignoreURI : ignoreURIS) { if(currentURI.contains(ignoreURI)){ isValid=true; if(log.isInfoEnabled()){ log.info("系統已跳過檢查以下url:"+currentURI); } } } if (!isValid) { if(log.isInfoEnabled()){ log.info("系統提示信息:URL為跨域請求,即將重定向到首頁。 "); } response.sendRedirect("/index.html"); } else { arg2.doFilter(arg0, arg1); } } public void init(FilterConfig arg0) throws ServletException { } }