//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 {
}
}
希望与广大网友互动??
点此进行留言吧!