package com.unis.base.server.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author zhanghonghuai
 *  
 *  处理查询字段为特殊字符时，查询结果错误问题
 *
 */
@Component
@WebFilter(filterName = "httpServletRequestWrapperFilter", urlPatterns = { "/base-server/*" })
public class HttpServletRequestWrapperFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;

            // 遇到post方法才对request进行包装
            String methodType = httpRequest.getMethod();
            // 只对post请求的select开头的方法生效
            String servletPath = httpRequest.getRequestURI().toString();
            //if ("POST".equals(methodType) && servletPath.contains("/select")) {
            if ("POST".equals(methodType)) {

                //BodyReaderHttpServletRequestWrapper的构造器内对请求体里的%进行处理
                requestWrapper = new BodyReaderHttpServletRequestWrapper(
                        (HttpServletRequest) request);
            }
        }

        if (null == requestWrapper) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }

    }

    @Override
    public void destroy() {

    }
}

