package org.fouram.core.filter;

import java.io.IOException;

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

import org.fouram.core.util.Tools;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartResolver;

public class MultipartResolverFilter implements Filter {
	
	// 用于创建MultipartHttpServletRequest  
	private MultipartResolver multipartResolver = null;  
	
	@Override
	public void init(FilterConfig fc) throws ServletException {
		// 注入bean  
		ServletContext context = fc.getServletContext();
		ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
		multipartResolver = (MultipartResolver) ctx.getBean("multipartResolver");
	}

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		ServletRequest req1 = getRequest(req);
		chain.doFilter(req1, res);
	}
	
	/** 
	 * 获取 request 
	 * @param req 
	 * @return 
	 */  
	private ServletRequest getRequest(ServletRequest req){  
	    String enctype = req.getContentType();  
	    if (Tools.notEmpty(enctype) && enctype.contains("multipart/form-data"))  
	        // 返回 MultipartHttpServletRequest 用于获取 multipart/form-data 方式提交的请求中 上传的参数  
	        return multipartResolver.resolveMultipart((HttpServletRequest) req);  
	    else   
	        return req;  
	}  
}
