过滤器
--Filter过滤器
Filter快速入门
Filter拦截路径
过滤器链
Filter——流程
import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import lombok.extern.slf4j.Slf4j;
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 LoginCheckFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//强转
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
//1.获取请求url
String url = req.getRequestURL().toString();
log.info("请求的url:{}", url);
//2.判断请求url中是否包含login,如果包含,说明是登陆操作,放行
if (url.contains("login")) {
log.info("登陆操作,放行...");
filterChain.doFilter(servletRequest, servletResponse);
return;
}
//3.获取请求头中的令牌(token)
String jwt = req.getHeader("token");
//4.判断令牌是否存在,如果不存在,返回错误结果(未登陆)
if (!StringUtils.hasLength(jwt)) {
log.info("请求头token为空,返回未登陆的信息");
Result error = Result.error("NOT_LOGIN"); //与前端约定好的
//手动转换 对象--json ----------> 阿里巴巴fastJSON
String notLogin = JSONObject.toJSONString(error);
resp.getWriter().write(notLogin); //将字符串响应给浏览器
return; //不会继续向下执行
}
//5.解析token,如果解析失败,返回错误结果(未登陆)
try {
JwtUtils.parseJWT(jwt);
} catch (Exception e) {//jwt解析失败
e.printStackTrace();
log.info("解析令牌失败,返回为登陆错误信息");
Result error = Result.error("NOT_LOGIN"); //与前端约定好的
//手动转换 对象--json ----------> 阿里巴巴fastJSON
String notLogin = JSONObject.toJSONString(error);
resp.getWriter().write(notLogin); //将字符串响应给浏览器
return;
}
//6.放行
log.info("令牌合法,放行");
filterChain.doFilter(servletRequest, servletResponse);
}
}
fastJSON依赖
<!--pom.xml-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
标签:JavaWeb,url,Filter,程序员,Result,error,过滤器,import,log
From: https://www.cnblogs.com/HanXuxian/p/18051778