SpringBoot配置拦截器的方法 - 极悦
专注Java教育14年 全国咨询/投诉热线:444-1124-454
极悦LOGO图
始于2009,口口相传的Java黄埔军校
首页 hot资讯 SpringBoot配置拦截器的方法

SpringBoot配置拦截器的方法

更新时间:2022-07-06 11:05:13 来源:极悦 浏览3156次

Java教程中大家会学到spring boot拦截器的配置,其实spring boot拦截器的配置方式和spring MVC类似。只需要注意一些小的变化。下面介绍两种常用的拦截器:

1.基于URL的拦截器:

public class LoginInterceptor extends HandlerInterceptorAdapter{
	/**
     * Call before request processing (before Controller method call)
     * Interceptor Based on URL
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getServletPath();
        if (path.matches(Const.NO_INTERCEPTOR_PATH)) {
        	//No need to intercept directly
            return true;
        } else {
        	// This describes the things you need to do to intercept, such as fetching cache, SESSION, permission judgment, etc
            System.out.println("====================================");
            return true;
        }
    }
}

关键代码:path.matches(const.no'intersector'path是基于正则匹配的url。

/**
 * @author 	BianP
 * @explain Constant class
 */
public class Const {
    public static final String SUCCESS = "SUCCESS";
    public static final String ERROR = "ERROR";
    public static final String FIALL = "FIALL";
    /**********************Objects and individuals****************************/
    public static final String SESSION_USER = "loginedAgent"; // User object
    public static final String SESSION_LOGINID = "sessionLoginID"; // Login ID
    public static final String SESSION_USERID = "sessionUserID"; // Current user object ID number
    public static final String SESSION_USERNAME = "sessionUserName"; // Current user object ID number
    public static final Integer PAGE = 10; // Default page number
    public static final String SESSION_URL = "sessionUrl"; // Recorded url
    public static final String SESSION_SECURITY_CODE = "sessionVerifyCode"; // Login page verification code
    // Time cache time
    public static final int TIMEOUT = 1800;// second
	public static final String ON_LOGIN = "/logout.htm";
	public static final String LOGIN_OUT = "/toLogout";
    // Do not validate URL anon: do not validate / authc: controlled
    public static final String NO_INTERCEPTOR_PATH =".*/((.css)|(.js)|(images)|(login)|(anon)).*";
}

2.基于注解的拦截器

(1)创建注解:

/**
 * Use this annotation on the method of the Controller that requires login authentication
 */
@Target({ElementType.METHOD})// Available on method name
@Retention(RetentionPolicy.RUNTIME)// Valid at run time
public @interface LoginRequired {	
}

(2)创建拦截器:

public class AuthorityInterceptor extends HandlerInterceptorAdapter{	
	 @Override
	 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
	 	// If it is not mapped to a method directly through
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // ①: START method annotation level interceptor
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // Determine whether the interface needs to be logged in
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        // With @ LoginRequired annotation, authentication is required
        if (methodAnnotation != null) {
            // This describes the things you need to do to intercept, such as fetching cache, SESSION, permission judgment, etc
            System.out.println("====================================");
            return true;
        }
        return true;
	}
}

(3)在配置中添加拦截器,相当于spring MVC中配置文件的作用:

/**
 * The same webmvc interception configuration as spring MVC
 * @author BIANP
 */
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {
	 @Override
	 public void addInterceptors(InterceptorRegistry registry) {
        // Block all requests, and determine whether login is required by judging whether there is @ LoginRequired annotation
        registry.addInterceptor(LoginInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**");
        super.addInterceptors(registry);
	 }	 
	 @Bean
	 public LoginInterceptor LoginInterceptor() {
		 return new LoginInterceptor();
	 }	 
	 @Bean
	 public AuthorityInterceptor AuthorityInterceptor() {
		 return new AuthorityInterceptor();
	 }
}

一定要添加@Configuration注解,它会在启动时加载。

其实spring MVC的很多东西都可以用在spring boot中。只需将Configuration文件的模式改为对应的@Configuration类即可。如果大家想了解更多相关知识,不妨来关注一下极悦的SpringBoot教程,里面的课程内容更加丰富,相信对大家的学习一定会有所帮助的。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>