实现 HandlerInterceptor 接口
package com.gary.interseptor;
/**
* @Description: 全局拦截器
*/
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.gary.exception.CustomException;
import com.gary.exception.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class LoginInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
@Resource
private RedisUtil redisUtil;
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
String uri = request.getRequestURI().toString();
logger.info(uri);
String token = request.getHeader("h-token");
if (null == token){
logger.error("no token error");
throw new CustomException(ErrorCode.NO_TOKEN_ERROR);
}
User user = TokenUtil.getIdentity(redisUtil, token);
if(user == null) {
logger.error("not login , token:{}",token);
throw new CustomException(ErrorCode.USER_NOT_LOGIN);
}
request.setAttribute("user", user);
return true;
}
}
约定登录成功后,将token放入到请求头中,拦截器从请求头中获取token,从redis中获取对应的用户信息,如果没有token返回没有token异常;如果没有用户信息,返回token过期异常。
2.WebMvcConfigurerAdapter
重写WebMvcConfigurerAdapter中的addInterceptors方法把自定义的拦截器类添加进来
package com.gary.interseptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter{
/**
* 拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/toLogin","/doLogin");
super.addInterceptors(registry);
}
}
3.测试访问