HttpServletRequestWrapper 类的重写

使用场景:
用于服务端修改request请求参数,适用于对跨站脚本的转义

package org.zhang.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class ParameterRequestWrapper extends HttpServletRequestWrapper
{
private static java.util.Hashtable hashParam = new Hashtable();

/**
* 继承父类构造函数
*/
public ParameterRequestWrapper(HttpServletRequest request)
{
super(request);
}

public String getParameter(String str)
{
return str = convert(super.getParameter(str));

}

/**
* 重写servlet中的getParameterMap()方法,用于封装转义之后的客户端参数
*
* @return requestParams 客户端参数Map集合
*/
public Map getParameterMap()
{
Map requestParams = super.getParameterMap();

Method method;

try
{
method = requestParams.getClass().getMethod("setLocked", new Class[] {boolean.class});
method.invoke(requestParams, new Object[] {new Boolean(false)});
}
catch (SecurityException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (NoSuchMethodException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}

// 遍历requestParams对象,转换匹配的字符
for (Iterator iterator = requestParams.keySet().iterator(); iterator.hasNext();)
{
String keyStr = (String)iterator.next();
String[] value = (String[])requestParams.get(keyStr);
for (int i = 0; i < value.length; i++)
{
value[i] = convert(value[i]);
}
requestParams.put(keyStr, value);

}
return requestParams;
}

public static String convert(String str)
{
for (Iterator it = getHashParam().keySet().iterator(); it.hasNext();)
{
String hashKey = (String)it.next();
String hashValue = (String)hashParam.get(hashKey);
if (str.indexOf(hashKey) != -1)
{
str = str.replace(hashKey, hashValue);
}
}
System.out.println(str);
return str;
}

public static java.util.Hashtable getHashParam()
{
hashParam.put("<", "<");
hashParam.put(">", ">");
return hashParam;
}

}

好的调试工具:dotnetfx.exe Fiddler2Setup.exe httpwatch_20063.exe

你可能感兴趣的:(Java,Servlet,脚本)