servlet過濾器filter對於reqeust請求的參數有兩種方式html
第一種 生成HttpServletRequest的代理類app
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
final HttpServletRequest request=(HttpServletRequest)arg0;
HttpServletResponse response=(HttpServletResponse)arg1;
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
HttpServletRequest proxy=(HttpServletRequest) Proxy.newProxyInstance(
request.getClass().getClassLoader(),
new Class[] {HttpServletRequest.class},
new InvocationHandler(){
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
//第一個代理對象 第二個目標方法 第三個目標方法參數
String methodName=method.getName();
if("getParameter".equals(methodName)){
String requestValue=request.getParameter(args[0].toString());
String submitMethod=request.getMethod();
if("get".equalsIgnoreCase(submitMethod)){
if(requestValue!=null && !"".equals(requestValue.trim())){
requestValue=new String(requestValue.getBytes("ISO8859-1"),"utf-8");
}
}
return requestValue;
}else{
//放行
return method.invoke(request, args);
}
}
});
arg2.doFilter(proxy, response);//必定要放行 而且request放行的是代理對象 不然沒法進入servlet
}ide
第二種 繼承HttpServletRequest的適配器HttpServletRequestWrapper的類spa
public class DataFilter implements Filter {
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)arg0;
HttpServletResponse response=(HttpServletResponse)arg1;
MyRequestData myRequest=new MyRequestData(request);
chain.doFilter(myRequest, response);
}代理
}htm
class MyRequestData extends HttpServletRequestWrapper{
public MyRequestData(HttpServletRequest request) {
super(request);
}
@Override
public String getParameter(String name){
String[] words={"nnd","nimabi","mabi"};
String value=super.getParameter(name);
for(String word:words){
if(value.contains(word)){
value="*************";
}
}
return value;
}
}對象