1. 程式人生 > >動態代理方式來解決全域性亂碼(get/post提交)

動態代理方式來解決全域性亂碼(get/post提交)

final HttpServletRequest req = (HttpServletRequest) request;
	// 使用動態代理完成全域性編碼
	HttpServletRequest enhanceRequest = (HttpServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(),
			req.getClass().getInterfaces(), new InvocationHandler() {

				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					// 對getParameter方法進行增強
					String name = method.getName();
					if ("getParameter".equals(name)) {
						String invoke = (String) method.invoke(req, args);// 亂碼的字串
						// 轉碼
						invoke = new String(invoke.getBytes("iso8859-1"), "utf-8");
						return invoke;
					}
					// 其他方法不管,原封不動的執行
					return method.invoke(req, args);
				}
			});
	chain.doFilter(enhanceRequest, response);