Springboot拦截器

     在web项目中,拦截器是不可或缺的,下面就拦截器来讲解一下代码

     首先,要自定义一个拦截器并继承  HandlerInterceptor 接口

package com.xyh.Config;

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;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String  flag = (String) session.getAttribute("user");
        if(null == flag){
            request.setAttribute("msg","您还未登录,请先登录");
            request.getRequestDispatcher("test").forward(request,response);
        }
        return true;
    }
}

 通过session获取是否已经登录,若已登录,则放行,return true,若session 为空,则表示并未登录,则返回一条msg,转发到你自己的登录界面,让用户先登录,再进行下面的操作。

  配置完自定义拦截器,还要在配置类里装配

package com.xyh;

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

@Configuration
public class MyConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/*")
                .excludePathPatterns("/test")
                .excludePathPatterns("/register")
                .excludePathPatterns("/log")
                .excludePathPatterns("/UserLogin")
                .excludePathPatterns("/file")
                .excludePathPatterns("/fileUpload")
                .excludePathPatterns("/toregister");
    }

}

 @configuration表明是一个配置类,然后继承了WebMvcConfigurer接口,重写它的addInterceptor方法,也就是它里面的关于拦截器的方法,把自己的类名称通过new的方式注入进来,然后.addPathPatterns("/*")表示拦截所有请求,..excludePathPatterns("")表示不拦截一些请求,引号里写自己不想被拦截的地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值