标签:自定义 irving springframework import 注解 拦截 annotation
# 自定义注解拦截器
### 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),"分页查询成功");
}
```
标签:自定义,irving,springframework,import,注解,拦截,annotation 来源: https://www.cnblogs.com/shiyerui/p/14983287.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。