spring boot添加拦截器【原创】

java技术文章

2019-05-27

12

0

struts2的拦截器功能是非常好用的,现在系统切换到spring boot,也想用拦截器实现一些通用的功能,比如用户验证。

下面是我的实现方式

一、添加依赖包:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

二、添加WebMvcConfigurerAdapter实现类

2.1、这里我为了添加多语言,所以多创建了一层CustomBaseMvcConfig类

/**
 * Project Name:mco.spring
 * File Name:CustomMvcConfig.java
 * Package Name:com.mco.spring.configure.model
 * Date:2019年5月22日下午3:03:18
 * Copyright (c) 2019, 649445087@qq.com All Rights Reserved.
 *
*/

package com.mco.spring.configure.model;

import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


/**
 * ClassName:CustomMvcConfig <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason:	 TODO ADD REASON. <br/>
 * Date:     2019年5月22日 下午3:03:18 <br/>
 * @author   LUOFUJIA
 * @version  
 * @jdk version JDK 1.8
 * @see 	 
 */
@SuppressWarnings("deprecation")
//@Configuration
public class CustomBaseMvcConfig extends WebMvcConfigurerAdapter {
    
    /** 
     * 配置自己的国际化语言解析器 
     * @return 
     */  
    @Bean  
    public LocaleResolver localeResolver() {  
        return new CustomLocaleResolver();  
    }  
}

2.2、然后继承CustomBaseMvcConfig类创建CustomMvcConfig

package com.mco.front.configure;

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

import com.mco.front.interceptor.AuthInterceptor;
import com.mco.spring.configure.model.CustomBaseMvcConfig;

@Configuration
public class CustomMvcConfig extends CustomBaseMvcConfig {

	 @Override
     public void addInterceptors(InterceptorRegistry registry) {
         //注册拦截器 拦截规则
        //多个拦截器时 以此添加 执行顺序按添加顺序
        registry.addInterceptor(getHandlerInterceptor()).addPathPatterns("/*").excludePathPatterns("/login*");
     }
     
    @Bean
    public static HandlerInterceptor getHandlerInterceptor() {
        return new AuthInterceptor();
    }
}

在上面类中添加拦截器AuthInterceptor,拦截除了登录/登出之外的URL。

三、最后是拦截器AuthInterceptor实现

package com.mco.front.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.mco.basic.exception.UncheckedException;
import com.mco.common.annotations.RestAuth;

public class AuthInterceptor implements HandlerInterceptor{
	
	private Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
		//获取控制器的名字
        System.out.println(((HandlerMethod) handler).getBean().getClass().getName());
        //获取方法名
        System.out.println(((HandlerMethod) handler).getMethod().getName());
		logger.info("preHandle:请求前调用");
        //返回 false 则请求中断
		RestAuth authorizeAnnotation = this.getAuthorizeAnnotation(handler);
		if (authorizeAnnotation != null) {
            
        }
        return true;
    }
 
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
    	logger.info("postHandle:请求后调用");
 
    }
 
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    	logger.info("afterCompletion:请求调用完成后回调方法,即在视图渲染完成后回调");
 
    }
    
    /**
     * 从Action类的方法中获取权限注解。
     * 
     * @param invocation
     *            ActionInvocation
     * @return 返回获取到的权限注解。
     */
    private RestAuth getAuthorizeAnnotation(Object handler) {
        try {
            Method method = ((HandlerMethod) handler).getMethod();
            RestAuth authorizeAnnotation = method.getAnnotation(RestAuth.class);
            if (authorizeAnnotation != null) {
                return authorizeAnnotation;
            } else {
                return ((HandlerMethod) handler).getBean().getClass().getAnnotation(RestAuth.class);
            }
        } catch (Exception e) {
            throw new UncheckedException("查找Authorize注解时发生异常。", e);
        }
    }

}

这样,我们就实现了一个拦截器,可以根据在拦截器中实现自己的逻辑。

欢迎访问:www.hongfu951.com博客,查看更多文章

发表评论

全部评论:0条

鸿福951

努力打造一个好用的webui

热评文章

推荐文章