1.概念
2.执行流程
3.WebConfig配置类
package com.hz.config;
import com.hz.interceptor.LoginCheckInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration//配置类
public class WebConfig implements WebMvcConfigurer {
@Autowired
private LoginCheckInterceptor loginCheckInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**").excludePathPatterns("/login");
}
}
4.LoginCheckInterceptor示例
package com.hz.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.hz.pojo.Result;
import com.hz.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
@Override//目标资源方法运行前运行,返回true,放行,返回false,不放行
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取请求url
String url = request.getRequestURL().toString();
log.info("请求的url: {}",url);
//判断请求的url中是否包含login
if(url.contains("login")){
log.info("登录操作,放行~~~");
//放行
return true;
}
//获取请求头中的令牌(token)
String jwt = request.getHeader("token");
//判断令牌是否存在,如不存在,则返回错误提示信息
if(!StringUtils.hasLength(jwt)){
log.info("请求头token为空,返回未登录的信息");
Result error = Result.error("NOT_LOGIN");
//手动转换
//对象 ---> JSON
String notLogin = JSONObject.toJSONString(error);
response.getWriter().write(notLogin);
return false;
}
//解析token,如果解析失败,返回错误结果
try {
JwtUtils.parseJWT(jwt);
} catch (Exception e) {
e.printStackTrace();
log.info("解析令牌失败,返回未登录的错误信息");
Result error = Result.error("NOT_LOGIN");
//手动转换
//对象 ---> JSON
String notLogin = JSONObject.toJSONString(error);
response.getWriter().write(notLogin);
return false;
}
//放行
log.info("令牌合法,放行~~~");
return true;
}
@Override//目标资源方法运行后运行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override//视图渲染完毕后运行,最后运行
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
标签:拦截器,入门,error,springframework,org,import,Interceptor,servlet,public
From: https://blog.csdn.net/2301_79690805/article/details/145174799