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 {
}
}