栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot设置拦截器

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot设置拦截器

1、创建我们自己的拦截器类并实现HandlerInterceptor接口。
2、创建-个Java类继承WebMvcConfigurerAdapter, 并写addInterceptors方法。
2、实例化我们自定义的拦截器,然后将对像手动添加到拦截器链中。

先来自定义一个MyInterceptor拦截器;
拦截器- -般需要继承HandlerInterceptor接口, 并需要实现以下三个接口
方法:

package com.newdo.base;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    //获取请求中的session
        String userCode = (String) request.getSession().getAttribute("UserCode");
        if (userCode==null){
           //跳转的地址
            request.getRequestDispatcher("/login").forward(request,response);
            return false;
        }
        return true;
    }

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

    }

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

    }
}

拦截器定义完成后,还需要将拦截器注册才能生效,并指定该拦截器所拦
截的场景。
创建MyWebMvcConfig继承WebMvcConfigurerAdapter,并重写
addInterceptors方法

package com.newdo.configuration;

import com.newdo.base.MyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class DefaultWebConfiguration implements WebMvcConfigurer {

    @Bean
    public MyInterceptor myInterceptor(){
        return new MyInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor())
                .addPathPatterns("/**") //拦截所有路径
                .excludePathPatterns("/login","/","/getValidCode")  //排除路径
                .excludePathPatterns("/static/**"); //排除静态资源路径
    }

跟拦截器相关的执行流程如下:

测试-直接访问主页,拦截器自动拦截所有请求,判断用户是否登录,否–跳转到登录页面

原文地址:https://www.cnblogs.com/wx60079/p/12841733.html

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/337083.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号