# 自定义注解拦截器
### 1.先自定义注解
如下所示,我们先自定义好注解,自定义注解往往需要定义该注解使用在什么地方,什么时间使用它
```java
@Target(ElementType.METHOD)//此处定义为方法级注解
@Retention(RetentionPolicy.RUNTIME)//表示运行的时候使用该注解
@Documented//生成javadoc的时候就会把@Documented注解给显示出来。
public @interface Login {
}
```
如下所示
```java
ackage com.irving.ir.config;
import com.irving.ir.common.util.JwtUtils;
import com.irving.ir.componet.AuthorizationInterceptor;
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.WebMvcConfigurer;
/**
* @author irving
* @date 2021/6/19
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private JwtUtils jwtUtils;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthorizationInterceptor(jwtUtils));
}
}
```
如下
```java
package com.irving.ir.componet;
import com.irving.ir.common.annotation.Login;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 自定义token处理逻辑
* @author irving
* @date 2021/6/19
*/
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Login annotation;
if (handler instanceof HandlerMethod){
annotation=((HandlerMethod)handler).getMethodAnnotation(Login.class);
}else {
return true;
}
if (annotation==null){
return true;
}
//具体需要拦截该注解的接口做什么操作
......
}
```
如下
```java
@ApiOperation("分页显示所有留言并按时间进行降序")
@RequestMapping(value = "/list/all", method = RequestMethod.GET)
@ResponseBody
@Login
public CommonResult<CommonPage<Board>> listBoard(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){
List<Board> boardList =boardService.queryAllBoard(pageNum,pageSize);
return CommonResult.success(CommonPage.restPage(boardList),"分页查询成功");
}
```