1、自定义一个注解
package com.example.demo.wb; import java.lang.annotation.*; //自定义注解,名叫WB @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @documented @Inherited public @interface WB { }
2、建一个controller,并在需要aop拦截的方法上添加自定义注解
package com.example.demo.wb; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @WB @RequestMapping("/myrequest") public String doRequest(){ return "已处理"; } }
3、编写AOP接口,最最最关节的注解是@Aspect
package com.example.demo.wb; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; @Aspect @Component public class MyAop { //切面连接处 @Pointcut("@annotation(com.example.demo.wb.WB)") public void cutMethod(){} @Before(value="cutMethod()") public void doCut() throws Exception { //获取请求属性 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); //获取请求对象 HttpServletRequest request = attributes.getRequest(); //获取请求头中的tt参数 String string=request.getHeader("tt"); System.out.println("请求头中的tt参数为:"+string); if(string==null){ //如果tt参数为空,抛异常 //也可做其他 *** 作 throw new Exception("请求头中的tt参数为空"); } } }
4、postman测试,发一个请求
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)