springBoot使用拦截器实现权限验证,解决注入为空

今天使用springboot配置了一个拦截器,拦截系统中的全部请求,实现的方式如下:

1、首先写一个注入拦截器的配置类

import com.gkcx.fls.inteceptor.SecurityInteceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    //将拦截器作为一个Bean写入配置里面
    @Bean
    public SecurityInteceptor securityInteceptor() {
        return new SecurityInteceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(securityInteceptor()).addPathPatterns("/**");
    }
}

2、写一个权限拦截器

import com.TManagerUser;
import com.TValidationPermissions;
import com.TValidationPermissionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 系统权限拦截器
 * @author run
 */
@Component  //将组件引入到spring容器中,让spring对其进行管理
public class SecurityInteceptor implements HandlerInterceptor {
    @Autowired
    private TValidationPermissionsService tValidationPermissionsService;

    //请求处理前调用
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //System.out.print("进入权限验证");
        
        return this.validationUserPermissions(httpServletRequest);//此处为需要设置的拦截规则
    }

    //请求处理后,视图渲染前调用
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    //请求处理后,视图渲染后调用
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

关键代码已经粘贴出来,其他代码就不粘贴出来了,写拦截器需要注意标红的两个地方,这样能够解决@Autowired注入为空的情况。

 

你可能感兴趣的:(springBoot,springboot拦截器,权限验证)