拦截器demo
程序员文章站
2022-05-23 10:45:40
...
下面展示一些 内联代码片
。
自定义注解:
/**
* @Author:
* @Date: 2020/4/30 10:10
*/
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyHandlerAnnonation {
boolean tokenNonNull() default true;
}
webConfig配置:
/ * @Date: 2020/5/8 14:53
*
* 启用拦截器
*/
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
registry.addInterceptor(new interceptor.MyInterCeptor()).addPathPatterns("/**").excludePathPatterns("/login");
}
}
interceptor:
package com.example.interceptor.interceptor;
import com.example.interceptor.annonation.MyHandlerAnnonation;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Author:
* @Date: 2020/5/8 15:06
*/
public class interceptor {
/**
* @Author:
* @Date: 2020/4/30 10:04
*/
@Component
public static class MyInterCeptor implements HandlerInterceptor {
private static final String TOKEN_HEADER = "token";
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod h = (HandlerMethod) handler;
if (h.getMethod().isAnnotationPresent(MyHandlerAnnonation.class) || h.getMethod().getDeclaringClass().isAnnotationPresent(MyHandlerAnnonation.class)) {
MyHandlerAnnonation annotation = h.getMethod().getAnnotation(MyHandlerAnnonation.class);
String token = request.getHeader(TOKEN_HEADER);
if (annotation.tokenNonNull() == false && StringUtils.isEmpty(token)) {
return true;
}
if(!token.equals("1223")||StringUtils.isEmpty(token)){
throw new Exception("无权限访问,请登录");
}
}
}
return true;
}
}
}
controller层:
@RestController
@RequestMapping("/yy")
public class MyController {
@GetMapping("/kkk")
@MyHandlerAnnonation()
public void testHandler() {
System.out.println("ffffffffffff");
}
}
推荐阅读
-
oracle存储过程demo分享
-
使用.Net Core + Vue + IdentityServer4 + Ocelot 实现一个简单的DEMO +源码
-
使用spring拦截器手写权限认证框架
-
jQuery插件HighCharts绘制的2D堆柱状图效果示例【附demo源码下载】
-
jQuery插件HighCharts实现的2D堆条状图效果示例【附demo源码下载】
-
vue2.0嵌套路由实现豆瓣电影分页功能(附demo)
-
详解flutter之网络请求dio,请求,拦截器简单示例
-
Android TCP 文件客户端与服务器DEMO介绍
-
android即时通讯demo开源(android studio实现聊天功能)
-
jsp页面验证码demo