您好,登錄后才能下訂單哦!
動態代理和靜態代理的區別
動態代理是在運行時,將代理類加載到內存中
靜態代理是提前把代理類寫好,然后再啟動項目的時候把代理類加載到內存中
動態代理
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
//0 強轉
final HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//1 post亂碼
request.setCharacterEncoding("UTF-8");
//2 使用動態代理增強request
HttpServletRequest proxyRequest = (HttpServletRequest)Proxy.newProxyInstance(
EncodingFilter.class.getClassLoader(),
new Class[] { HttpServletRequest.class } ,
new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//增強
String methodName = method.getName();
if("getParameter".equals(methodName)){
//args 所有參數 --> getParameter("username");
//1 從tomcat request獲得原始數據(亂碼)
String value = request.getParameter((String)args[0]);
//2 如果get請求處理亂碼
if("GET".equals(request.getMethod())){
value = new String( value.getBytes("ISO-8859-1") , "UTF-8");
}
//3 將結果返回
return value;
}
//不需要增強的直接執行目標類的方法
return method.invoke(request, args);
}
});
chain.doFilter(proxyRequest, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
靜態代理(裝飾者模式)
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
//0 強轉
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//1 post亂碼
request.setCharacterEncoding("UTF-8");
//2 使用裝飾者增強request
MyRequest myRequest = new MyRequest(request);
chain.doFilter(myRequest, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
/**
增強response對象,提供使用裝飾者設計模式編寫默認類:HttpServletResponseWrapper
*/
public class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request; //tomcat request
public MyRequest(HttpServletRequest request){
super(request);
this.request = request;
}
//增強
@Override
public String getParameter(String name) {
//1 直接從tomcat的request獲得數據
String value = this.request.getParameter(name);
//2 如果是get,處理
// * 請求方式
String method = this.request.getMethod();
if("GET".equals(method)){
try {
value = new String( value.getBytes("ISO-8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return value;
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。