package com.zuxia.filter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
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.dom4j.Document;
import com.zuxia.xml.ParseXML;
public class ParamsFilter implements Filter {
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)req;
HttpServletResponse response = (HttpServletResponse)resp;
//获取到请求的路径
String path = request.getRequestURI();//firtServlet_docheckLogin
if(path.indexOf(".servlet")==-1){
chain.doFilter(request, response);
}
else{
path = path.substring(path.lastIndexOf("/")+1);//获取
到"firtServlet_docheckLogin"
String data[] = path.replace(".servlet", "").split("_");
String class_name = data[0];//表示servlet的名
String method_name = data[1];//表示方法名
//读取配置文件
ParseXML parse = new ParseXML();
Document doc = parse.loadXML();
String class_url = parse.getClassPath(doc, class_name);
try {
//创建好了Servlet的对象
Object server_obj = Class.forName(class_url).newInstance();
Field fds[] = server_obj.getClass().getDeclaredFields();
//获取表单提交上来的所有值
Map params = request.getParameterMap
();//name=value,pwd=value
for(Field fd : fds){
fd.setAccessible(true);
Iterator iter = params.keySet().iterator();
while(iter.hasNext()){
String key = iter.next()+"";
if(fd.getName().equalsIgnoreCase(key)){
fd.set(server_obj, ((String[])
params.get(key))[0]);
break;
}
}
}
//调用StudentServlet的方法
Method mds[] = server_obj.getClass().getMethods();
for(Method md : mds){
if(md.getName().equalsIgnoreCase(method_name)){
md.invoke(server_obj);//动态的执行指定方法
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
//如何跳转到指定页面?
}
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub