spirngboot拦截器

对于管理系统或其他需要用户登录的系统,登录验证都是必不可少的环节,在 SpringBoot 开发的项目中,通过实现拦截器来实现用户登录拦截并验证。

1.SpringBoot 实现登录拦截的原理

SpringBoot 通过实现HandlerInterceptor接口实现拦截器,通过实现WebMvcConfigurer接口实现一个配置类,在配置类中注入拦截器,最后再通过 @Configuration 注解注入配置.

2.实现 HandlerInterceptor 接口

引入依赖:

 <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
package com.yxkj.spring_aop_demo.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.util.Map;

/**
 * @USER: 文 俊
 * @DATE: 2021-07-15
 * @description:功能描述
 */
public class MyHandlerInterceptor implements HandlerInterceptor {
    /***
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行了拦截器的preHandle方法");
        StringBuffer json = new StringBuffer();
        String line = null;
        String username= "";
        JSONObject jsonObject =null;
       // HttpSession session = request.getSession();
        try {
            //统一拦截(查询请求路径是否存在admin信息)
//            String username = request.getParameter("user");
            BufferedReader reader = request.getReader();
            while((line = reader.readLine()) != null) {
                json.append(line);
            }
            jsonObject =  JSON.parseObject(json.toString());
         
            username = jsonObject.get("user").toString();
            if(username.equals("admin")){
                return true;
            }
            return false;
        }catch (Exception e){
          e.printStackTrace();
        }
        return false;
        //如果设置为false时,被请求时,拦截器执行到此处将不会继续操作
        //如果设置为true时,请求将会继续执行后面的操作
    }
    /***
     * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("执行了拦截器的postHandle方法");
    }
    /***
     * 整个请求结束之后被调用,也就是在DispatchServlet渲染了对应的视图之后执行(主要用于进行资源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("执行了拦截器的afterCompletion方法");
    }
}

3.实现 WebMvcConfigurer 接口,注册拦截器

@Configuration
public class MyConfiguration implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //注册MyHandlerInterceptor拦截器
        InterceptorRegistration registration =  registry.addInterceptor(new MyHandlerInterceptor());
        registration.addPathPatterns("/**");////所有路径都被拦截
        registration.excludePathPatterns(    //添加不拦截路径
                "/login",                    //登录路径
                "/**/*.html",                //html静态资源
                "/**/*.js",                  //js静态资源
                "/**/*.css"                  //css静态资源
        );
    }
}

4.controller层

@RestController
@RequestMapping(value = "/login")
public class LongUserController {

    @RequestMapping(value = "/index",method = RequestMethod.POST)
    public String login(){
        return "登录成功!";
    }

    @RequestMapping(value = "/error",method = RequestMethod.GET)
    public String error(){
        System.out.println("登录失败!");
        return "登录失败!";
    }
}

5.测试

image

posted @ 2021-07-15 18:27  风飘落叶  阅读(42)  评论(0编辑  收藏  举报