package com.library.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class CharsetFilter implements Filter {
	private String enconding;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		resp.setContentType("text/html;charset="+enconding);
		chain.doFilter(new servletreq((HttpServletRequest) req), resp);
//		System.out.println("--------");
	}

	@Override
	public void init(FilterConfig con) throws ServletException {
		// TODO Auto-generated method stub
		enconding=con.getInitParameter("encode") ==null ? "utf-8" :con.getInitParameter("encode");
	}
	
//	����һ���µ������� 
	class servletreq extends HttpServletRequestWrapper{
		private HttpServletRequest request;
		private boolean isNotEncode = true;
		public servletreq(HttpServletRequest request) {
			super(request);
			this.request=request;
		}
		public Map<String, String[]> getParameterMap(){
			try {
			if(request.getMethod().equals("POST")){
				request.setCharacterEncoding(enconding);
				return request.getParameterMap();
			}else if(request.getMethod().equals("GET")){
				Map<String, String[]> map=request.getParameterMap();
				if(isNotEncode){
					for(Map.Entry<String, String[]> entry: map.entrySet()){
						String[] value=entry.getValue();
						for(int i=0;i<value.length;i++){
								value[i]=new String(value[i].getBytes("iso-8859-1"),"utf-8");
						}
					}
					isNotEncode=false;
				}
				return map;
			}else{
				return request.getParameterMap();
			}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		public String[] getParameterValuse(String name){
			return getParameterMap().get(name);
		}
		public String getParameter(String name){
			return getParameterMap().get(name)==null?null:getParameterMap().get(name)[0];
		}
	}

}
