@WebFilter(urlPatterns = "/*")
public class LoginChechedFilter implements Filter {
//拦截方法,只要资源链接被拦截就会触发此方法
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest) servletRequest;
HttpServletResponse response= (HttpServletResponse) servletResponse;
//获取请求路径,为login则放行
String url=request.getRequestURI().toString(); //http://localhost:8080/login
//判断url有无login
if(url.contains("login")){
//登录功能,放行
filterChain.doFilter(servletRequest,servletResponse);
return;
}
else {
//获取请求头Token,只要登录成功,就存储了Token
String jwt= request.getHeader("token");
if(jwt==null){
//返回登录页面
Result not_login= Result.error("NOT_LOGIN");
//把not_login转为Json
String josnString=JSONObject.toJSONString(not_login);
//给客户端响应数据,给前端返回json{"code":0,"msg":"NOT_LOGIN","data":null}
response.getWriter().write(josnString);
return;
}
//解析token
try{
GernerateToken.parseJWT(jwt);}
catch (Exception e){
//令牌存在问题
Result not_login= Result.error("NOT_LOGIN");
//把not_login转为Json
String josnString=JSONObject.toJSONString(not_login);
//给客户端响应数据,给前端返回json{"code":0,"msg":"NOT_LOGIN","data":null}
response.getWriter().write(josnString);
return;
}
//令牌认证成功,放行
filterChain.doFilter(servletRequest,servletResponse);
}
}