package com.itjiandan.servlet;
import java.io.IOException;
import java.util.Map;
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.HttpSession;
import com.itjiandan.model.User_Entity;
import com.itjiandan.util.LogUtil;
public class WebFilter implements Filter {
    private String setChar;
    private String myform;
    private String method;
    private String key;
    private String path;
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        LogUtil.i("销毁过滤器...");
    }
    @SuppressWarnings("unchecked")
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
            request.setCharacterEncoding(this.setChar);
            response.setCharacterEncoding(this.setChar);
            HttpServletRequest req = (HttpServletRequest) request;
            HttpSession hs = req.getSession();
            this.myform = req.getParameter("myform");
            this.method = req.getParameter("method");
            User_Entity user = (User_Entity) hs.getAttribute("#user#");
            Map myAMap = null;
            this.key = this.myform + "|" + this.method;
            this.path = req.getServletPath() + "?" + req.getQueryString();
              
            LogUtil.i("myform and method:"+this.key + "\npath:" + this.path);
              
              
         if(this.method == null && this.myform == null)
            {
                chain.doFilter(req, response);
                return;
            }
            if("login".equals(this.myform))
            {
                if(user != null){
                      
                    LogUtil.i("user="+user.getName());
                    if("logout".equals(method)){
                        chain.doFilter(req, response);
                        return;
                    }
                    req.getRequestDispatcher("/WEB-INF/admin/index.jsp").forward(request, response);
                    return;
                }
                chain.doFilter(req, response);
                return;
            }
            if(user != null)
            {
                myAMap = (Map) hs.getAttribute("#myAMap#");
                String aPath = myAMap.get(this.key);
                  
                if(aPath != null){
                    LogUtil.i("权限列表:" + aPath);
                    chain.doFilter(req, response);
                    return;
                }
                  
            }
    }
    @Override
    public void init(FilterConfig config) throws ServletException {
          this.setChar = config.getInitParameter("SetChar");
          LogUtil.i("执行初始化参数...");
    }
}