package com.sys.controller;


import java.io.IOException;
import java.util.Date;
import java.util.UUID;

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.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;

import com.cku.model.CkuMatchLogger;
import com.sys.service.CkuMatchLoggerUtil;

public class LogFilter implements Filter{
	private static final Logger logger = Logger.getLogger(LogFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("----过滤器初始化----");
	}

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

		// TODO Auto-generated method stub
		//对request和response进行一些预处理
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String uri = httpRequest.getRequestURI();
		HttpSession httpSession = httpRequest.getSession();
		logger.info("uri========"+uri+";params========"+httpRequest.getParameterMap()+"====");
		//入库
		CkuMatchLogger logger = new CkuMatchLogger();
		logger.setAddTime(new Date());
		logger.setId(UUID.randomUUID().toString());
		logger.setMethod(httpRequest.getMethod());
		logger.setUrl(uri);
		logger.setRemoteAddr(httpRequest.getRemoteAddr().toString());
		if (httpSession != null && httpSession.getAttribute("userId") != null) {
			logger.setUserId(httpSession.getAttribute("userId").toString());
		}
		logger.setParam(httpRequest.getParameterMap().toString());
		CkuMatchLoggerUtil.saveLoggerToDB(logger);  
		
		
		
		if(uri.indexOf("login.jsp")>-1 || uri.indexOf("sys/login.do")>-1){
			chain.doFilter(request, response);  //让目标资源执行，放行
			return;
		}

		if (httpSession == null || httpSession.getAttribute("user") == null) {
			String contenxtPath = httpRequest.getContextPath();
			String servletPath = httpRequest.getServletPath();
			httpResponse.sendRedirect(contenxtPath + "/login.jsp");
		}else{
			chain.doFilter(request, response);  //让目标资源执行，放行
			
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("----过滤器销毁----");
	}
	
}
