Java-注解拦截器

一:环境

  1. 创建个spring boot 2.1.2版本
  2. 有个能正常调用的接口

二:pom配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.41</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

三:创建个注解类

package com.example.demo.config;

import java.lang.annotation.*;

/**
 * @author huang(jy)
 * @version 1.0
 * @date 2020/5/8 14:39
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
//是否需要登录拦截
public @interface NeedLogin {
	//是否需要登录拦截,默认不需要
    boolean needLoginValue() default false;

}

四:创建自定义拦截器类

package com.example.demo.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


/**
 * @author huang(jy)
 * @version 1.0
 * @date 2020/5/8 14:48
 */
public class NeedLoginInterceptors implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否有注解
        boolean isNeed = handler.getClass().isAssignableFrom(HandlerMethod.class);
        if (isNeed) {
            //获取到这个注解信息
            NeedLogin needLogin = ((HandlerMethod) handler).getMethodAnnotation(NeedLogin.class);
            if (needLogin != null && needLogin.needLoginValue()) {
                return true;
            }
        }
        //重置response
        response.reset();
        //设置编码格式
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(JSONObject.toJSONString("无权限"));
        return false;
    }

}

五:拦截器注入WebMvcConfigurerAdapter

package com.example.demo.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author huang(jy)
 * @version 1.0
 * @date 2020/5/8 15:05
 */
@Component
public class WebMvcConfigurerAdapter implements WebMvcConfigurer {


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册NeedLoginInterceptors拦截器
        InterceptorRegistration registration = registry.addInterceptor(new NeedLoginInterceptors());
        registration.addPathPatterns("/**");//拦截所有路径
    }
}

六:测试是否生效
1.注解为:true,结果如下图
Java-注解拦截器_第1张图片
2.注解不填,默认为false,结果如下图(返回为拦截器里的提示信息)
Java-注解拦截器_第2张图片
3.不写注解,结果如下(返回为拦截器里的提示信息);
Java-注解拦截器_第3张图片

总结:

创建注解类
自定义拦截器实现 HandlerInterceptor类,重写preHandle方法,在其实现判断逻辑
注入自定义的拦截器,实现WebMvcConfigurer ,重写addInterceptors方法,配置拦截所有路径

如有转载请请务必保留此出处:https://blog.csdn.net/hometing218/article/details/105998169

你可能感兴趣的:(Java,拦截器,java)