SpringBoot 优雅的配置拦截器方式

2021-02-17 00:17

阅读:725

标签:步骤   runtime   name   oid   基于   run   wired   param   verify   

步骤:

1.实现WebMvcConfigurer配置类

2.实现拦截器

3. 把拦截器添加到配置中

4.添加需要拦截的请求

5.添加需要排除的请求

 1 package com.zp.springbootdemo.interceptor;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
 6 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 7 
 8 /**
 9  * 和springmvc的webmvc拦截配置一样
10  * @author zp
11  */
12 @Configuration
13 public class WebConfigurer implements WebMvcConfigurer {
14     /**
15      * 拦截器配置
16      * @param registry
17      */
18     @Override
19     public void addInterceptors(InterceptorRegistry registry) {
20         // addPathPatterns拦截所有请求,excludePathPatterns排除特殊的请求
21         //registry.addInterceptor(LoginInterceptor()).addPathPatterns("/**");
22         registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**");
23         //excludePathPatterns 排除的请求
24 //        registry.addInterceptor(LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/**");
25 //        registry.addInterceptor(AuthorityInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/**");
26     }
27     /**
28      * 拦截器一
29      * @return
30      */
31     @Bean
32     public LoginInterceptor LoginInterceptor() {
33         return new LoginInterceptor();
34     }
35     /**
36      * 拦截器二
37      * @return
38      */
39     @Bean
40     public AuthorityInterceptor AuthorityInterceptor() {
41         return new AuthorityInterceptor();
42     }
43 }

基于URL实现的拦截器:

 1 package com.zp.springbootdemo.interceptor;
 2 
 3 import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 4 
 5 import javax.servlet.http.HttpServletRequest;
 6 import javax.servlet.http.HttpServletResponse;
 7 
 8 public class LoginInterceptor extends HandlerInterceptorAdapter {
 9     /**
10      * 在请求处理之前进行调用(Controller方法调用之前)
11      * 基于URL实现的拦截器
12      * @param request
13      * @param response
14      * @param handler
15      * @return
16      * @throws Exception
17      */
18     @Override
19     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
20         String path = request.getServletPath();
21         System.out.println("当前请求路径:"+path);
22         System.out.println("=========进入拦截器1===================");
23         if (path.matches(Const.NO_INTERCEPTOR_PATH)) {
24             //不需要的拦截直接过
25             System.out.println("=========无需拦截===================");
26             return true;
27         } else {
28             System.out.println("=========开始拦截===================");
29             // 这写你拦截需要干的事儿,比如取缓存,SESSION,权限判断等
30             String token = request.getParameter("token");
31             if(token == null){
32                 System.out.println("=========拦截完成==================="+false);
33                 return false;
34             }
35             System.out.println("=========拦截完成==================="+true);
36             return true;
37         }
38     }
39 }

关键代码:path.matches(Const.NO_INTERCEPTOR_PATH 就是基于正则匹配的url。

package com.zp.springbootdemo.interceptor;

/**
 * @author   zp
 * @explain 常量类
 */
public class Const {

    public static final String SUCCESS = "SUCCESS";
    public static final String ERROR = "ERROR";
    public static final String FIALL = "FIALL";
    /**********************对象和个体****************************/
    public static final String SESSION_USER = "loginedAgent"; // 用户对象
    public static final String SESSION_LOGINID = "sessionLoginID"; // 登录ID
    public static final String SESSION_USERID = "sessionUserID"; // 当前用户对象ID编号

    public static final String SESSION_USERNAME = "sessionUserName"; // 当前用户对象ID编号
    public static final Integer PAGE = 10; // 默认分页数
    public static final String SESSION_URL = "sessionUrl"; // 被记录的url
    public static final String SESSION_SECURITY_CODE = "sessionVerifyCode"; // 登录页验证码
    // 时间 缓存时间
    public static final int TIMEOUT = 1800;//
    public static final String ON_LOGIN = "/logout.htm";
    public static final String LOGIN_OUT = "/toLogout";
    // 不验证URL anon:不验证/authc:受控制的
    public static final String NO_INTERCEPTOR_PATH =".*/((.css)|(.js)|(images)|(login)|(anon)).*";
}

测试:

请求地址:http://127.0.0.1:8080/user/getUser?token=123

结果:

 技术图片

 

 

基于注解的拦截器

①创建注解:

package com.zp.springbootdemo.interceptor;

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

/**
 * 在需要登录验证的Controller的方法上使用此注解
 */
@Target({ElementType.METHOD})// 可用在方法名上
@Retention(RetentionPolicy.RUNTIME)// 运行时有效
public @interface LoginRequired {

}

②创建拦截器:

package com.zp.springbootdemo.interceptor;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class AuthorityInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("===============进入拦截器2=====================");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            System.out.println("===============无需拦截=====================");
            return true;
        }
        // ①:START 方法注解级拦截器
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判断接口是否需要登录
        LoginRequired methodAnnotation = method.getAnnotation(LoginRequired.class);
        // 有 @LoginRequired 注解,需要认证
        if (methodAnnotation != null) {
            // 这写你拦截需要干的事儿,比如取缓存,SESSION,权限判断等
            System.out.println("===============开始拦截=====================");
            String token = request.getParameter("token");
            if(token == null){
                System.out.println("=========拦截完成==================="+false);
                return false;
            }
            System.out.println("=========拦截完成==================="+true);
            return true;
        }
        System.out.println("===============无需拦截===================");
        return true;
    }
}

测试接口代码1:

package com.zp.springbootdemo.system.controller;

import com.zp.springbootdemo.interceptor.LoginRequired;
import com.zp.springbootdemo.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/getUser")
    //@LoginRequired
    public Map getUser(@RequestParam Map user){
       return userService.getUser(user);
    }
}

请求地址:

http://127.0.0.1:8080/user/getUser?token=123

结果:

技术图片

测试接口代码2:

package com.zp.springbootdemo.system.controller;

import com.zp.springbootdemo.interceptor.LoginRequired;
import com.zp.springbootdemo.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/getUser")
    @LoginRequired
    public Map getUser(@RequestParam Map user){
       return userService.getUser(user);
    }
}

请求地址:

http://127.0.0.1:8080/user/getUser?token=123

结果:

 技术图片

 

SpringBoot 优雅的配置拦截器方式

标签:步骤   runtime   name   oid   基于   run   wired   param   verify   

原文地址:https://www.cnblogs.com/zhangpeng8888/p/12702305.html


评论


亲,登录后才可以留言!