spring boot通过自定义注解和AOP拦截指定的请求

时间:2022-07-07 20:35:44

一 准备工作

1.1 添加依赖

通过spring boot创建好工程后,添加如下依赖,不然工程中无法使用切面的注解,就无法对制定的方法进行拦截

 <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-aop</artifactId>
 </dependency>

 

1.2 工程目录结构

其中 

MonitorRequest 自定义注解
RequestAspect 切面类
BookController 测试接口请求

spring boot通过自定义注解和AOP拦截指定的请求

 

二 自定义注解

package com.tinno.word.advice;

import java.lang.annotation.*;
import org.springframework.web.bind.annotation.Mapping;

/**
 * Created by xingle on 2019/5/15
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Mapping
@Documented
public @interface MonitorRequest {


}

三 切面类

 

 1 package com.tinno.word.aspect;
 2 
 3 import com.tinno.word.utils.CodeUtils;
 4 import javax.servlet.http.HttpServletRequest;
 5 import org.aspectj.lang.ProceedingJoinPoint;
 6 import org.aspectj.lang.annotation.Around;
 7 import org.slf4j.Logger;
 8 import org.slf4j.LoggerFactory;
 9 import org.springframework.web.context.request.RequestContextHolder;
10 import org.springframework.web.context.request.ServletRequestAttributes;
11 
12 /**
13  * Created by xingle on 2019/5/15
14  * 此类为一个切面类,主要作用就是对接口的请求进行拦截
15  * 拦截的方式,只需要在指定接口方法上面加上@MonitorRequest注解即可
16  */
17 
18 @Aspect
19 @Component
20 public class RequestAspect {
21 
22   private Logger logger = LoggerFactory.getLogger(this.getClass());
23 
24   /**
25    * 环绕通知:
26    * 环绕通知非常强大,可以决定目标方法是否执行,什么时候执行,执行时是否需要替换方法参数,执行完毕是否需要替换返回值。
27    * 环绕通知第一个参数必须是org.aspectj.lang.ProceedingJoinPoint类型
28    */
29   @Around(value = "@annotation(com.tinno.word.advice.MonitorRequest)")
30   public Object doBefore(ProceedingJoinPoint joinPoint) {
31 
32     //获取到请求的属性
33     ServletRequestAttributes attributes =
34         (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
35     //获取到请求对象
36     HttpServletRequest request = attributes.getRequest();
37 
38     //获取请求的方法,是Get还是Post请求
39     logger.info("method=" + request.getMethod());
40 
41     Object[] args = joinPoint.getArgs();
42     String de_input = "";
43     try {
44       logger.debug("请求参数 解密前:" + args[0].toString());
45       //这里具体解密方法不再列出
46       de_input = CodeUtils.decrypt(args[0].toString());
47       logger.debug("请求参数 解密后:" + de_input);
48     } catch (Exception e) {
49       e.printStackTrace();
50     }
51     args[0] = de_input;
52 
53     Object returnValue = null;
54     try {
55       //执行方法,以新的参数(如果不带args就是用原先的参数)
56       returnValue = joinPoint.proceed(args);
57       logger.debug("returnValue 加密前:" +returnValue.toString());
58     } catch (Throwable throwable) {
59       throwable.printStackTrace();
60     }
61     //执行完毕也可以替换目标方法返回值,这里加密替换,也可以不加密原样返回
62     returnValue = CodeUtils.encrypt(returnValue.toString());
63     logger.debug("returnValue 加密后:" +returnValue.toString());
64     return returnValue;
65 
66   }
67 
68 
69 }

 

四 Controller类

 

 1   @MonitorRequest
 2   @RequestMapping(value = "/getBookVersionLs", method = {RequestMethod.GET,RequestMethod.POST},produces={"text/html;charset=UTF-8;","application/json;"})
 3   public String getBookVersionLs(@RequestBody String json){
 4     logger.info("Controller-getBookVersionLs 版本选择书本列表,请求参数:"+json);
 5     JSONObject jsonObject = JSONObject.parseObject(json);
 6     String userId = jsonObject.getString("udid");
 7     String device_id = jsonObject.getString("device_id");
 8     Map<String, Object> data = JsonUtil.jsonText2JsonMap(jsonObject.getString("data"));
 9 
10     String rand = data.get("rand").toString();
11     String version =  data.get("version").toString();
12 
13     if (isEmpty(userId) || isEmpty(device_id)){
14       ResultBody result = ResultBody.toFailure(ErrorInfoEnum.PARAMS_NO_COMPLETE.getStatus(),ErrorInfoEnum.PARAMS_NO_COMPLETE.getDest());
15       return new Gson().toJson(result);
16     }
17     List<AllBookVersion> allList = bookService.getAllBookVersionLs();
18     AllBookVersion first = allList.get(0);
19     if (isEmpty(rand) && isEmpty(version)){
20       rand = first.getRand();
21       version = first.getVersionLs().get(0);
22     }
23     List<BookVersion> bookList = bookService.getBookVersionLs(device_id,rand,version);
24 
25     JSONObject obj = new JSONObject();
26     obj.put("bookList",bookList);
27     obj.put("allList",allList);
28     ResultBody resultBody = ResultBody.toSussess(obj,"");
29     return new Gson().toJson(resultBody);
30   }

 

四 结果

请求参数:

D1D329BF7D4C02CB97C29CB03DF243D79A280D3DD1C6B0EC89B353394409DE0C950A48E2809E6539DE3A641CBA6A89957296D9E7E1DD4906505C5ADFAF89C0AA0B585B1338A57F1CAD8ABE8538E74B75C7947C0B593E3C6DB66DB2CDE07305B671E4405FFA5701C44590D3DE4973174E7D8FB983E82768A0DE086534494CAA49

 

返回结果:

加密后的结果