实现类:
@Slf4j
@WebFilter("/*")
public class LoginCheckFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
// 1. 请求和响应对象的强转
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// 2. 获取请求uri
// uri:/login url: http://localhost:90/login
String uri = request.getRequestURI();
log.info("uri的值是: {}", uri);
// 3. 判断请求uri是否是登录,如果是就放行
if ("/login".equals(uri)) {
filterChain.doFilter(request, response);
return;
}
// 4. 走到这行一定不是登录,获取请求头的token (令牌)
String token = request.getHeader("token");
// 5. token不存在,返回前端未登录
if (token == null || token.equals("")) {
String json = new ObjectMapper().writeValueAsString(Result.error("NOT_LOGIN"));
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
return;
}
// 6. 解析token,如果解析失败,返回前端未登录
try {
JwtUtils.parseJWT(token);
} catch (Exception e) {
// 出现异常,token校验不通过,返回错误提示
String json = new ObjectMapper().writeValueAsString(Result.error("NOT_LOGIN"));
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
return;
}
// 7. 放行
filterChain.doFilter(request, response);
}
}
启动类:
// 启动类,位置必须高于其他类
@SpringBootApplication // 启动类注解
@MapperScan("com.itheima.mapper") // 指定mapper接口所在的包
@EnableAspectJAutoProxy // 开启aop
@ServletComponentScan // 开启过滤器
public class SpringBootDemoApplication {
// springboot内置了tomcat,端口号默认8080 (约定大于配置)
public static void main(String[] args) {
// 固定写法
// 参数一:启动类.class
// 参数二:args
SpringApplication.run(SpringBootDemoApplication.class, args);
}
}