spring-java-oriented aspect interceptor

        Aspect means that when the code is executed, something can be added in front of it. Generally, we use it to verify login interceptors and filter sensitive words.

        He only has 3 things, specify the cut point (the code to be executed), and add something before the code is executed. Add something after the after code. Generally we only use pointcuts and before.

1. Introduce related dependencies

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

2. passToken annotation (optional)

Mainly to make the annotated interface accessible, such as login and registration

package xxxx

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 不需要做登录验证的加上当前注解
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
    boolean required() default true;
}

3. Section

Here you need to write a return method sendJsonMessage to return information

package com.dengta.tanzhiwcustomermarket.config;


import com.alibaba.fastjson.JSONObject;
import com.dengta.tanzhiwcustomermarket.tools.RedisUtils;
import com.dengtacj.tanzhiw.common.api.ResultCode;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Aspect
@Configuration
public class ControllerAspect {

    private final static Logger logger = LoggerFactory.getLogger(ControllerAspect.class);

    // 定义切点Pointcut  自行写入对应的controller包路径
    @Pointcut("execution(* com.dengta.tanzhiwcustomermarket.controller.*.*(..))")
    public void pointCut() {
    }

    @Before("execution(* com.dengta.tanzhiwcustomermarket.controller.*.*(..))&&!@annotation(com.dengta.tanzhiwcustomermarket.config.PassToken)")
    public void before(JoinPoint joinPoint) throws Throwable {
        //获取token
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String accessToken = request.getHeader("authorization");
        HttpServletResponse response = requestAttributes.getResponse();
        if(accessToken==null){//没有token直接结束
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",500);
            jsonObject.put("message","暂未登录或token已经过期");

            sendJsonMessage(response,jsonObject);//必须要有这个
            return;//放行
        }
    }

    public static void sendJsonMessage(HttpServletResponse response, Object obj) {
        try {
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(200);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(obj.toString().getBytes("UTF-8"));
            outputStream.close();
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Test Results

 

Supongo que te gusta

Origin blog.csdn.net/qq_38403590/article/details/131641076
Recomendado
Clasificación