Spring Boot 2.X 如何添加拦截器?

最近使用SpringBoot2.X搭建了一个项目,大部分接口都需要做登录校验,所以打算使用注解+拦截器来实现,在此记录下实现过程。

 

一、实现原理

1. 自定义一个注解@NeedLogin,如果接口需要进行登录校验,则在接口方法或类方法上添加该注解。
2. 登录拦截器LoginInterceptor校验接口的方法或类上是否有@NeedLogin注解,有注解则进行登录校验。

二、主要代码

1. NeedLogin注解代码

package com.example.helloSpringBoot.annotation;

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

/**
 * 登录注解
 *
 * @Author: Java碎碎念
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NeedLogin {
}

2. 登录拦截器LoginInterceptor

package com.example.helloSpringBoot.config;

import com.example.helloSpringBoot.annotation.NeedLogin;
import com.example.helloSpringBoot.util.WxUserInfoContext;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 登录拦截器
 *
 * @Author: Java碎碎念
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    //这个方法是在访问接口之前执行的,我们只需要在这里写验证登陆状态的业务逻辑,就可以在用户调用指定接口之前验证登陆状态了
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            NeedLogin needLogin = ((HandlerMethod) handler).getMethodAnnotation(NeedLogin.class);
            if (null == needLogin) {
                needLogin = ((HandlerMethod) handler).getMethod().getDeclaringClass()
                        .getAnnotation(NeedLogin.class);
            }
            // 有登录验证注解,则校验登录
            if (null != needLogin) {
                WxUserInfoContext curUserContext = (WxUserInfoContext) request.getSession()
                        .getAttribute("curUserContext");
                //如果session中没有,表示没登录
                if (null == curUserContext) {
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write("未登录!");
                    return false;
                }
            }

        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    }
}

3. 配置拦截器

package com.example.helloSpringBoot.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * WebConfig
 *
 * @Author: Java碎碎念
 *
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private LoginInterceptor loginInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 自定义拦截器,添加拦截路径和排除拦截路径
        registry.addInterceptor(loginInterceptor).addPathPatterns("/**");
    }
}

三、验证代码

HelloController中添加两个方法,testNeedLogin()方法添加登录拦截,testNoLogin()方法不需要登录拦截。

package com.example.helloSpringBoot.controller;

import com.example.helloSpringBoot.annotation.NeedLogin;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    /**
     * 测试不 需要登录
     *
     *
     */
    @RequestMapping("/testNoLogin")
    public String testNoLogin (){
        return "调用成功,此接口不需要登录校验!-Java碎碎念!";
    }

    /**
     * 测试需要登录
     *
     *
     */
    @NeedLogin
    @RequestMapping("/testNeedLogin")
    public String testNeedLogin (){
        return "testNeedLogin!";
    }
}

testNeedLogin运行截图如下:

testNoLogin运行截图如下:

  

上述三步操作完成后即可实现登录拦截,有问题欢迎留言沟通哦!

完整源码地址:https://github.com/suisui2019/helloSpringBoot

 

推荐阅读

1.Spring Boot 2.X 如何优雅的解决跨域问题?
2.Redis Cluster搭建高可用Redis服务器集群
3.为什么单线程的Redis这么快?
4.Spring Boot集成spring session实现session共享
5.Spring Boot入门-快速搭建web项目
6.Spring Boot2.0整合Redis
7.一篇文章搞定SpringMVC参数绑定
8.SpringMVC+Mybatis 如何配置多个数据源并切换?

 

限时领取免费Java相关资料,涵盖了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo/Kafka、Hadoop、Hbase、Flink等高并发分布式、大数据、机器学习等技术。

资料传送门:  https://mp.weixin.qq.com/s/u2b_NVNuMuAPE0w4lc45fw

关注下方公众号即可免费领取:

Java碎碎念公众号

posted @ 2019-04-18 16:23  Java碎碎念  阅读(3955)  评论(3编辑  收藏  举报