package com.ehking.demo.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import java.io.IOException;

public class CharacterEncodingFilter implements Filter{
    static final Logger LOGGER = LoggerFactory.getLogger(CharacterEncodingFilter.class);
    
    
    private String encoding;

    private boolean forceEncoding = false;

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public void setForceEncoding(boolean forceEncoding) {
        this.forceEncoding = forceEncoding;
    }


    public void init(FilterConfig filterConfig) throws ServletException {
        this.encoding = filterConfig.getInitParameter("encoding");
        String forceEncodingStr = filterConfig.getInitParameter("forceEncoding");
        if(StringUtils.isNotBlank(forceEncodingStr)){
            this.forceEncoding = Boolean.valueOf(forceEncodingStr);
        }
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (this.encoding != null && (this.forceEncoding || request.getCharacterEncoding() == null)) {
            request.setCharacterEncoding(this.encoding);
            if (this.forceEncoding) {
                response.setCharacterEncoding(this.encoding);
                response.setContentType("text/html; charset="+this.encoding);
            }
        }
        chain.doFilter(request, response);
    }

    public void destroy() {
        
    }
}
