Interceptor.java 1.47 KB
package vion.interceptor;

import cn.hutool.core.lang.Opt;
import cn.hutool.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import vion.Global;
import vion.enums.ResultEnum;
import vion.vo.UserVO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class Interceptor implements HandlerInterceptor {

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

            return true;
        }
        UserVO user = Opt.ofBlankAble(request.getHeader("token")).map(Global.USERNAME_MAP::get).orElse(null);
        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.set("code", ResultEnum.ATOKEN_ERROR.getCode());
            jsonObject.set("msg", "请先登陆再访问!");
            pw.write(jsonObject.toString());
            pw.flush();
            pw.close();
            return false;
        } else {
            request.setAttribute("start", System.currentTimeMillis());
            return true;
        }
    }
}