登陆拦截器

拦截器
package com.ustcinfo.fn.config;

import com.ustcinfo.fn.annotation.UnInterception;
import com.ustcinfo.fn.sys.dto.tbmUser;
import com.ustcinfo.fn.util.BaseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
<!--more-->
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author Jamin
 * @date 2020/10/15 17:21
 * 自定义拦截器
 */
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      log.info("[拦截地址]=>>>>>>" + request.getRequestURI());
      if (handler instanceof HandlerMethod) {
         HandlerMethod handlerMethod = (HandlerMethod) handler;
         Method method = handlerMethod.getMethod();
         String methodName = method.getName();
         UnInterception unInterception = method.getAnnotation(UnInterception.class);
         //有注解
         if (null != unInterception) {
            return true;
         }
      }
      tbmUser sessionUser = BaseUtil.getSessionUser();
      //session有对象
      if (null != sessionUser) {
         return true;
      }
      //重定向到登陆页
      response.sendRedirect(request.getContextPath() + "/");
      return false;
   }

}
注册拦截器
package com.ustcinfo.fn.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 拦截器
 *
 * @author Jamin
 * @date 2020/10/15 17:18
 */
@Configuration
public class MyInterceptorConfig implements WebMvcConfigurer {
	/**
	 * 添加拦截器     拦截全局 排除静态资源
	 *
	 * @param registry
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**")
				//排除静态资源
				.excludePathPatterns("/css/**", "/js/**", "/plugins/**", "/images/**")
				.excludePathPatterns("/error/**");
	}
}

注解

package com.ustcinfo.fn.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 不拦截注解
 *
 * @author Jamin
 * @date 2020/10/15 17:26
 */

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UnInterception {

}
作者: JaminYe
版权声明:本文原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文地址:https://www.cnblogs.com/JaminYe/p/13940695.html