当前位置: 首页 > article >正文

spring-java面向切面拦截器

        切面,就是可以在代码执行的时候,在它执行的前面添加一个东西,一般我们用来做登陆拦截器验证以及敏感词的过滤。

        他就3个东西,指定切点(要执行的代码),before代码执行前面加东西。after代码后加东西。一般我们只用切点和before。

1.引入相关依赖

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

2.passToken注解(可有可无)

主要是为了让加注解的接口可以访问,比如说登陆和注册

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.切面

这里需要写一个返回方法 sendJsonMessage,用于返回信息

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();
        }
    }
}

测试结果

 


http://www.kler.cn/a/37292.html

相关文章:

  • C/C++服务器和客户端交互笔记
  • MySQL (select查询的基本用法及select相关练习)
  • Linux操作系统——第五章 进程信号
  • 2. CSS3的新特性
  • SpringBoot + Kotlin 中使用 GRPC 进行服务通信
  • re学习(15)BUUCTF 2019红帽杯easyRe
  • 常用化合物谱图数据库查询系统-40个软件免费查!
  • 四、评估已建立的模型
  • 如何系统学习分布式?
  • Flink实时任务性能调优
  • 复习java基础
  • 中国移动光猫设置桥接
  • C++结合EasyX写扫雷(new)
  • window.getComputedStyle
  • 【Linux后端服务器开发】管道设计
  • 2023大数据面试总结
  • 【C#】并行编程实战:同步原语(1)
  • jquery html特殊字符反转义,JS - 实现HTML标签的转义、反转义的几种方法
  • Boundless Hackathon @Stanford 主题黑客松活动闭幕,一文回顾
  • 解决小程序 scroll-view 里面的image有间距、小程序里面的图片之间有空隙的问题。