Filter对Request的改变:HttpServletRequestWrapper的工作原理
8)Filter对Request的改变:HttpServletRequestWrapper的工作原理
马 克-to-win:有了HttpServletResponseWrapper的基础,就好理解HttpServletRequestWrapper了。 无疑它就是想在Request到达服务器之前,先把它处理一下。比如过滤掉一些政治敏感字。意义嘛,也好理解。比如n个html页面都需要过滤,如果都在 n个servlet当中过滤的话,会造成未来代码维护困难。马克-to-win:HttpServletRequestWrapper的使用方法就是靠 着:1)MarkToWinRequestWrapper hsr =new MarkToWinRequestWrapper((HttpServletRequest)request); 和 2)chain.doFilter(hsr, response);
这两句话以后MarkToWinRequestWrapper的实例hsr取 代了request,之后在servlet调用的request.getParameter(String name)方法当然就是MarkToWinRequestWrapper类的getParameter方法。如果servlet想调用request的其 他方法,MarkToWinRequestWrapper这个类也可以覆盖掉它。
例 1.2.8
package com;
import javax.servlet.http.*;
public class MarkToWinRequestWrapper extends HttpServletRequestWrapper {
public MarkToWinRequestWrapper(HttpServletRequest request) {
super(request);
}
public String getParameter(String param) {
System.out.println("参数是 is" + param);
String paramValue = super.getParameter(param);
System.out.println("修改前 in wrapper" + paramValue);
if (param.equals("name")) {
paramValue = paramValue.replaceAll("mark-to-win", "马克-to-win");
System.out.println("修改后 in wrapper" + paramValue);
} else if (param.equals("age")) {
paramValue = paramValue.replaceAll("30", "40");
System.out.println("修改后 in wrapper" + paramValue);
}
return paramValue;
}
}
package com;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.PrintWriter;
public class MarkToWinFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
MarkToWinRequestWrapper hsr =new MarkToWinRequestWrapper((HttpServletRequest)request);
/*下句话以后hsr取代了request,之后在servlet调用的request.getParameter(String name)方法当然就是MarkToWinRequestWrapper类的getParameter方法*/
chain.doFilter(hsr, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
更多内容请见原文,原文转载自:https://blog.csdn.net/qq_44638460/article/details/104093079