当前位置 : 主页 > 编程语言 > c++ >

动态代理实现web过滤器

来源:互联网 收集:自由互联 发布时间:2021-07-03
动态代理实现web过滤器 public class CharacterFilter implements Filter {public void destroy() {}public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws IOException, ServletException {final HttpServletR
动态代理实现web过滤器
public class CharacterFilter implements Filter {

	public void destroy() {
		
	}

	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {

		final HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		
		request.setCharacterEncoding("UTF-8");
		
		chain.doFilter((ServletRequest) Proxy.newProxyInstance(CharacterFilter.class.getClassLoader(), request.getClass().getInterfaces(), new InvocationHandler() {
			
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				if(!method.getName().equals("getParameter")){
					return method.invoke(request, args);
				}
				if(!request.getMethod().equalsIgnoreCase("get")){
					return method.invoke(request, args);
				}
				String value = (String) method.invoke(request, args);
				if(value==null){
					return null;
				}
				return new String(value.getBytes("iso8859-1"),"UTF-8");
			}
		}), response);
	
	}

	public void init(FilterConfig arg0) throws ServletException {
		
	}

}
网友评论