SpringBoot+SpringAOP的五种通知实现

首先增加Maven依赖

<dependency>
			<groupId>com.springframework.bootgroupId>
			<artifactId>spring-boot-starter-aopartifactId>
		dependency>
		<dependency>
			<groupId>org.aspectjgroupId>
			<artifactId>aspectjrtartifactId>
			<version>1.6.11version>
		dependency>
		<dependency>
			<groupId>org.aspectjgroupId>
			<artifactId>aspectjweaverartifactId>
			<version>1.6.11version>
		dependency>
		<dependency>
			<groupId>org.assertjgroupId>
			<artifactId>assertj-coreartifactId>
		dependency>

之后创建一个Aspect切面类

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Component
@Aspect
public class WebLogger {
     
    @Pointcut("execution(* com.nevergetme.nevergetmeweb.controller..*.*(..))")
    public void executeService(){
     
    }
    @Before("executeService()")
    public void doBeforeAdvice(JoinPoint joinPoint){
     
        System.out.println("我是前置通知!!!");
        //获取目标方法的参数信息
        Object[] obj = joinPoint.getArgs();
        //AOP代理类的信息
        joinPoint.getThis();
        //代理的目标对象
        joinPoint.getTarget();
        //用的最多 通知的签名
        Signature signature = joinPoint.getSignature();
        //代理的是哪一个方法
        System.out.println(signature.getName());
        //AOP代理类的名字
        System.out.println(signature.getDeclaringTypeName());
        //AOP代理类的类(class)信息
        signature.getDeclaringType();
        //获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        //如果要获取Session信息的话,可以这样写:
        //HttpSession session = (HttpSession) requestAttributes.resolveReference(RequestAttributes.REFERENCE_SESSION);
        Enumeration<String> enumeration = request.getParameterNames();
        Map<String,String> parameterMap = new HashMap<>();
        while (enumeration.hasMoreElements()){
     
            String parameter = enumeration.nextElement();
            parameterMap.put(parameter,request.getParameter(parameter));
        }
        System.out.println(parameterMap);
    }
    @After("executeService()")
    public void returnAfter(JoinPoint joinPoint){
     
        System.out.println("AOP after");
    }
    @AfterReturning(value="executeService()",returning = "result")
    public void afterReturning(JoinPoint joinPoint,Object result){
     
        System.out.println("AOP afterRuturning:"+result);
    }
    @AfterThrowing(value = "executeService()",throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint,Exception ex){
     
        System.out.println("AOP afterThrowing:"+ex);
    }
    @Around(value = "executeService()")
    public Object aroundLogging(ProceedingJoinPoint joinPoint){
     
        Object result=null;
        try {
     
            System.out.println("around before");
            result=joinPoint.proceed();
            System.out.println("around return"+result);
        } catch (Throwable throwable) {
     
            System.out.println("around exception:"+throwable);
        }
        System.out.println("around after");
        return result;
    }
}

com.nevergetme.nevergetmeweb.controller是一个请求处理类,可以自己写,我写的如下,实现了一个简单的关键词过滤

@RestController
@EnableAutoConfiguration
public class WebController {
     
    //ApplicationContext

    private static final SensitivewordFilter filter = new SensitivewordFilter();
    @RequestMapping("/hello")
    public String index(){
     
        return "Hello World";
    }
    @CrossOrigin
    @RequestMapping(value = "/sensitiveword",method = RequestMethod.POST)
    public @ResponseBody
    Map<String,String> getSensitiveWord(String words, HttpServletRequest request){
     
        Map<String,String> map=new HashMap<>();
        String output=filter.replaceSensitiveWord(words,1,"*");
        map.put("state","1");
        map.put("output",output);
        map.put("input",words);
        map.put("ip",request.getRemoteAddr());
        return map;
    }
    @CrossOrigin
    @RequestMapping(value = "/uploadTxt",method=RequestMethod.POST)
    public @ResponseBody Map<String,String> seneitiveWordTxt(@RequestParam(value="file")MultipartFile file)throws Exception{
     
//        String originFilename=file.getOriginalFilename();
        Map<String,String> map=new HashMap<>();
        if(file.isEmpty()){
     
            map.put("state","false");
            map.put("output","");
            return map;
        }
        System.out.println(file.getOriginalFilename());
        BufferedReader reader=new BufferedReader(new InputStreamReader(file.getInputStream()));
        StringBuffer sb=new StringBuffer();
        String line=null;
        String output="";
        try {
     
            while ((line=reader.readLine())!=null){
     
                sb.append(line);
            }
            System.out.println(sb.toString());
            output=filter.replaceSensitiveWord(sb.toString(),1,"*");
        }catch (IOException e){
     
            e.printStackTrace();
        }finally {
     
            if(output.length()>0){
     
                map.put("output",output);
                map.put("state","true");
            }else{
     
                map.put("state","false");
                map.put("output","");
            }
            return map;
        }

    }
}

然后运行得到结果如下
SpringBoot+SpringAOP的五种通知实现_第1张图片
可以看到执行顺序是
拦截器preHandle->Around Before->Before->Around return->Around After->After->After return->postHandle->afterCompletion

你可能感兴趣的:(JavaWeb)