1. 程式人生 > 其它 >自定義註解攔截請求

自定義註解攔截請求

# 自定義註解攔截器

### 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),"分頁查詢成功");

}
```