后端登陆的过滤器
package com.itheima.filter;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.util.StringUtils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
@WebFilter(urlPatterns="/*")
public class DemoFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException { //初始化方法只调用一次
Filter.super.init(filterConfig);
System.out.println("初始执行");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
System.out.println("执行前逻辑");
// 放行没有这句会没有数据
HttpServletRequest request=(HttpServletRequest) servletRequest;
HttpServletResponse response=(HttpServletResponse) servletResponse;
String url=request.getRequestURL().toString();
if(url.contains("login")||url.contains("Login")||url.contains(".html")){
log.info("登录");
chain.doFilter(servletRequest,servletResponse);
return ;
}
String jwt=request.getHeader("Token");
if(!StringUtils.hasLength(jwt)){
log.info("未登录");
Result error=new Result().error("Not_Login");
String notLogin= new Gson().toJson(error);
response.getWriter().write(notLogin);
return ;
}
try {
JwtUtils.parseJwt(jwt);
} catch (Exception e) {
log.info("解析令牌出错");
e.printStackTrace();
Result error=new Result().error("Not_Login");
String notLogin= new Gson().toJson(error);
response.getWriter().write(notLogin);
return ;
}
System.out.println(jwt);
log.info("令牌合法");
chain.doFilter(servletRequest,servletResponse);
System.out.println("执行后逻辑");
}
@Override
public void destroy() { //销毁方法只调用一次
Filter.super.destroy();
System.out.println("销毁执行");
}
}
标签:Result,System,println,登陆,error,过滤器,import,out From: https://www.cnblogs.com/luo9tian/p/17973895