文章目录
配置JwtInterceptor
-
-
- 配置JwtInterceptor
- InterceptorConfig的配置
- 测试
-
在com.tensquare.user.interceptor包下,创建JwtInterceptor拦截器 内容如下 该拦截器实现了HandlerInterceptor 接口. 重写了preHandle方法,代表在请求的之前进行一些操作. 如果preHandle方法返回true,代表放行该接口,如果返回false,代表该请求被拦截了. 并在该方法类,写了一段输出语句,如果经过了拦截器,那么就会打印这段话
package com.tensquare.user.interceptor; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 类名称:JwtInterceptor * 类描述:jwt的全局拦截器 * * @author: taohongchao * 创建时间:2019/2/16 13:56 * Version 1.0 */ @Component public class JwtInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("经过了拦截器"); //return true代表放行, return false 代表不放行 return true; } }InterceptorConfig的配置
在com.tensquare.user.config包写,编写拦截器的配置类 该配置类,继承了WebMvcConfigurationSupport 类,重写了addInterceptors方法. 在addInterceptors方法内, 拦截所有的请求,但是放行登录的请求.
package com.tensquare.user.config; import com.tensquare.user.interceptor.JwtInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; /** * 类名称:InterceptorConfig * 类描述: 拦截器的配置类 * * @author: taohongchao * 创建时间:2019/2/16 14:00 * Version 1.0 */ @Configuration public class InterceptorConfig extends WebMvcConfigurationSupport { @Autowired private JwtInterceptor jwtInterceptor; /** * 方法名: addInterceptors * 方法描述: 添加拦截器的规则 * 修改日期: 2019/2/16 14:02 * @param registry * @return void * @author taohongchao * @throws */ @Override protected void addInterceptors(InterceptorRegistry registry) { //添加jwt的拦截器 registry.addInterceptor(jwtInterceptor) //拦截所有的请求 .addPathPatterns("/**") //放行登录的请求 .excludePathPatterns("/**/login/**"); } }测试
启动tensquare_user项目.
发送一个该项目任意的请求,
例如查询所有的管理员
http://localhost:9008/admin
控制台打印如下,代表经过了拦截器,配置成功