Interceptor.java
1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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;
}
}
}