您好,登錄后才能下訂單哦!
動態(tài)代理和靜態(tài)代理的區(qū)別
動態(tài)代理是在運行時,將代理類加載到內(nèi)存中
靜態(tài)代理是提前把代理類寫好,然后再啟動項目的時候把代理類加載到內(nèi)存中
動態(tài)代理
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
//0 強轉(zhuǎn)
final HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//1 post亂碼
request.setCharacterEncoding("UTF-8");
//2 使用動態(tài)代理增強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 所有參數(shù) --> getParameter("username");
//1 從tomcat request獲得原始數(shù)據(jù)(亂碼)
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 將結(jié)果返回
return value;
}
//不需要增強的直接執(zhí)行目標類的方法
return method.invoke(request, args);
}
});
chain.doFilter(proxyRequest, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
靜態(tài)代理(裝飾者模式)
public class EncodingFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
//0 強轉(zhuǎn)
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對象,提供使用裝飾者設(shè)計模式編寫默認類: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獲得數(shù)據(jù)
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;
}
}
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。