Interceptor.java 1.86 KB
package vion.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Opt;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import vion.Global;
import vion.enums.ResultEnum;
import vion.model.User;
import vion.service.IUserSerrvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Interceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        System.out.println("拦截器");
        if(url.indexOf("login") >= 0){

            return true;
        }
        User user= Global.USERNAME_MAP.get(request.getHeader("userid"));
        if(user==null){
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter pw = response.getWriter();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msg_code", ResultEnum.ATOKEN_ERROR.getCode());
            jsonObject.put("msg_info", "请先登陆再访问!");
            pw.write(JSON.toJSONString(jsonObject));
            pw.flush();
            pw.close();
            return false;
        }
        request.setAttribute("userid", user.getUserid());
        request.setAttribute("start", System.currentTimeMillis());
        return super.preHandle(request, response, handler);
    }
}