今天使用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使用拦截器实现权限验证,解决注入为空】
推荐阅读
- springboot|Springboot+Shiro+Vue博客管理系统
- springboot|搭建一个springboot+templates+mysql+mybatisplus代码生成器简单框架
- SpringBoot|计算机毕业设计及论文-原创(基于SpringBoot的奥运村服务管理平台的设计与实现)
- vue+springboot|基于vue+springboot的校园疫情健康打卡和离校审批系统的设计 (百度地图API对接)
- springBoot|SpringBoot整合Spring Security+JWT实现前后端分离登录权限处理
- springboot|spring boot多数据源动态切换, 多数据源事务管理
- springboot|从零开始搭建springboot项目骨架
- 技术分享|使用 SpringBoot + Redis + Vue3 + ArcoPro 开发管理系统
- java|Eureka 时代之后的 Consul