1 16 package dlog4j.proxy; 17 18 import java.lang.reflect.InvocationHandler ; 19 import java.lang.reflect.InvocationTargetException ; 20 import java.lang.reflect.Method ; 21 import java.lang.reflect.Proxy ; 22 import java.util.HashMap ; 23 import java.util.Iterator ; 24 import java.util.Map ; 25 26 import javax.servlet.ServletException ; 27 import javax.servlet.ServletRequest ; 28 import javax.servlet.http.HttpServletRequest ; 29 30 31 36 public class RequestProxy implements InvocationHandler 37 { 38 final static String METHOD_GP = "getParameter"; 39 final static String METHOD_GPM = "getParameterMap"; 40 final static String METHOD_GPN = "getParameterNames"; 41 final static String METHOD_GPV = "getParameterValues"; 42 43 final static String ENC_8859_1 = "8859_1"; 44 final static String ENC_UTF_8 = "UTF-8"; 45 46 protected String encoding; 47 48 public String getEncoding() { 49 return encoding; 50 } 51 public void setEncoding(String encoding) { 52 this.encoding = encoding; 53 } 54 55 private ServletRequest req; 56 57 64 public final static RequestProxy getProxy(ServletRequest req, String encoding) throws ServletException { 65 return new RequestProxy(req, encoding); 66 } 67 68 private RequestProxy(ServletRequest req, String encoding){ 69 this.req = req; 70 this.encoding = encoding; 71 } 72 73 76 public Object invoke(Object proxy, Method m, Object [] args) throws Throwable { 77 Object obj = null; 79 String encode = (encoding==null)?ENC_UTF_8:encoding; 80 try{ 81 obj = m.invoke(req, args); 82 if(obj!=null){ 83 String mn = m.getName(); 84 if(METHOD_GP.equals(mn)){ 85 String value = (String )obj; 86 obj = new String (value.getBytes(ENC_8859_1),encode); 87 } 88 else 89 if(METHOD_GPV.equals(mn)){ 90 String [] values = (String [])obj; 91 for(int i=0;i<values.length;i++) 92 values[i] = new String (values[i].getBytes(ENC_8859_1),encode); 93 obj = values; 94 } 95 else 96 if(METHOD_GPM.equals(mn)){ 97 Map params = (Map )obj; 98 HashMap new_params = new HashMap (); 99 Iterator iter = params.keySet().iterator(); 100 while(iter.hasNext()){ 101 String key = (String )iter.next(); 102 Object oValue = params.get(key); 103 if(oValue.getClass().isArray()){ 104 String [] values = (String [])params.get(key); 105 for(int i=0;i<values.length;i++) 106 values[i] = new String (values[i].getBytes(ENC_8859_1),encode); 107 new_params.put(key, values); 108 } 109 else{ 110 String value = (String )params.get(key); 111 String new_value = (value!=null)? 112 new String (value.getBytes(ENC_8859_1),encode):null; 113 new_params.put(key,new_value); 114 } 115 } 116 } 117 } 118 }catch(InvocationTargetException e){ 119 throw e.getTargetException(); 120 } 121 return obj; 122 } 123 124 127 public HttpServletRequest getInstance(){ 128 return (HttpServletRequest )Proxy.newProxyInstance( 129 req.getClass().getClassLoader(), 130 request_cls, 131 this); 132 } 133 final static Class [] request_cls = new Class []{HttpServletRequest .class}; 134 } | Popular Tags |