package com.saye.hospitalgd.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
public class XssFilter implements Filter {
	
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException  {

        
        HttpServletRequest httpRequest  = (HttpServletRequest)request;
        HttpSession session = httpRequest.getSession(false);

        String requestURI = httpRequest.getRequestURI();
        if("/login".equals(requestURI)){
            if ( session != null && !session.isNew() ) {
                //首先将原session中的数据转移至一临时map中
                Map<String,Object> tempMap = new HashMap();
                Enumeration<String> sessionNames = session.getAttributeNames();
                while(sessionNames.hasMoreElements()){
                    String sessionName = sessionNames.nextElement();
                    tempMap.put(sessionName, session.getAttribute(sessionName));
                }

                //注销原session，为的是重置sessionId
                session.invalidate();

                //将临时map中的数据转移至新session
                session = httpRequest.getSession();
                for(Map.Entry<String, Object> entry : tempMap.entrySet()){
                    session.setAttribute(entry.getKey(), entry.getValue());
                }
            }
        }


        XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
        filterChain.doFilter(xssRequest, response);
    }

    @Override
    public void destroy() {
    }
    
    @Override
    public void init(FilterConfig filterConfig) {
        
    }
}