Filter 实现乱码过滤

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		final HttpServletRequest req = (HttpServletRequest)request;
		
		HttpServletRequest myReq = (HttpServletRequest) Proxy.newProxyInstance(EncodingFilter.class.getClassLoader(), req.getClass().getInterfaces(),
				new InvocationHandler(){

					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						
						if("getParameter".equals(method.getName())){
							
							//这边得到的是 GET,所以要用 equalsIgnoreCase
							if("get".equalsIgnoreCase(req.getMethod())){
								
								//对于get请求, 先执行 method.invoke获取要转换的数据
								//obj - 从中调用底层方法的对象
								//args - 用于方法调用的参数 
								String value = (String) method.invoke(req, args);
								String newValue = new String(value.getBytes("ISO-8859-1"),"GBK");
								return newValue;
							}else if("post".equalsIgnoreCase(req.getMethod())){
								req.setCharacterEncoding("GBK");
								Object obj = method.invoke(req, args); 
								return obj;
							}
						}
						
						return method.invoke(req, args);
					}
			
		});
		
		//此处传递的是 代理对象 myReq
		chain.doFilter(myReq, response); 
	}

猜你喜欢

转载自blog.csdn.net/xldmx/article/details/84991917
今日推荐