Web过滤器,解决未登录用户跳转登录页的功能
Servlet过滤器
过滤器由Servlet提供,拦截器是springmvc提供
功能
通过配置过滤器,来实现未登录的用户访问后台页面的时候直接跳转到登录页面
后台代码范例
@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
/**
* 路径匹配器,针对通配符的这种东西实现匹配的逻辑
*/
public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
log.info("拦截到请求: {}",request.getRequestURI());
/**
* 获取本次请求uri
*/
String requestURI = request.getRequestURI();
/**
* 定义不需要处理的请求路径
*/
String[] urls = new String[]{
"/employee/login",
"/employee/logout",
"/backend/**",
"/front/**"
};
/**
* 判断本次请求是否需要处理
*/
boolean check = check(urls, requestURI);
if (check){
// 放行
log.info("本次请求不需要处理")
filterChain.doFilter(request,response);
return;
}
/**
* 判断登录状态,如果已登录,则直接放行
*
*/
if (request.getSession().getAttribute("employee") != null){
log.info("用户已登录")
filterChain.doFilter(request,response);
return;
}
/**
* 通过输出流的方式向客户端页面响应数据
*/
log.info("用户未登录")
response.getWriter().write(JSON.toJSONString(Result.error(Status.ARGUMENT_ERROR)));
return;
}
/**
* 检查当前请求是否需要放行
* @param urls
* @param requestURI
* @return
*/
public boolean check(String[] urls,String requestURI){
for (String url : urls) {
boolean match = PATH_MATCHER.match(url, requestURI);
if (match){
return true;
}
}
return false;
}
}
springboot启动类上加注解@ServletComponentScna,这个@WebFilter才能生效
前端实现,搭配跳转登录页
前端vue中使用前端内置interceptor去实现,基于返回code和msg,根据接口返回的内容进行匹配,判断当前页面是否需要强制跳转到指定的登录页面中去
service.interceptors.response.use(res => {
const code = res.data.code;
const msg = res.data.msg;
if (res.data.code === 0 && res.data.msg === 'NOTLOGIN') {
localStorage.removeItem("userInfo")
window.top.location.href = '/backend/page/login/login.html'
}else{
return res.data
}
},
error => {
let ( message == "Network Error" ) {
message = "后端接口连接异常";
}
}
)
原创:做时间的朋友