单点登录配合拦截器使用案例
1.定义拦截器:
//定义用户拦截器 public class UserInterceptor implements HandlerInterceptor{ @Autowired private JedisCluster jedisCluster; private ObjectMapper objectMapper = new ObjectMapper(); /** * 1.获取用户Cookie获取token数据 * 2.判断token中是否有数据 * false 表示没有登陆,则重定向到用户登陆页面 * * true :表示用户之前登陆过 * 从redis中根据token获取userJSON, * 再次判断数据是否有数据 * * false: 没有数据,则重定向到用户登陆页面 * true : 表示有数据,则程序予以放行. */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //1.获取Cookiez中的token String token = null; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if("JT_TICKET".equals(cookie.getName())){ token = cookie.getValue(); break; } } //2.判断token是否有数据 if(token != null){ //2.1判断redis集群中是否有数据 String userJSON = jedisCluster.get(token); if(userJSON != null){ User user = objectMapper.readValue(userJSON,User.class); //将user数据保存到ThreadLocal中 UserThreadLocal.set(user); //证明用户已经登陆 予以放行 return true; } } //配置重定向 response.sendRedirect("/user/login.html"); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { //关闭threadLocal UserThreadLocal.remove(); } }
2.配置拦截器
<!--配置拦截器 ((bean | ref) | interceptor)+ bean 拦截器的bean标签 <ref/> 对象的引用 <mvc:mapping path=""/> 拦截器拦截的路径 <mvc:exclude-mapping path=""/> 不需要拦截的路径 path="/cart/*" 只能拦截/cart/一级目录 path="/cart/**" 拦截/cart/全部目录 定义单个拦截器 Content Model : (mapping+, exclude-mapping*, (bean | ref)) --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/cart/**"/> <mvc:mapping path="/order/**"/> <bean class="com.jt.web.interceptor.UserInterceptor"/> </mvc:interceptor> </mvc:interceptors>