package com.muyu.system.interceptor;

import com.muyu.system.holder.DataSourceContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @Author：张腾
 * @Package：com.muyu.system.interceptor
 * @Project：cloud-server-8
 * @name：DataSourceInterceptor
 * @Date：2024/9/18 19:40
 */
public class DataSourceInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求当中获取数据源标识符
        String database = request.getParameter("database");
        if (null != database){
            DataSourceContextHolder.setDatasourceMsg(database);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //请求完成之后进行清理操作
        DataSourceContextHolder.clearDataSourceKey();
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求完成之后进行清理操作
        DataSourceContextHolder.clearDataSourceKey();
    }


}
