SpringBoot中拦截器

拦截器在springboot中只需要实现HandlerInterceptor接口,并重写preHandle方法

package com.hzy.config;

import org.springframework.web.servlet.HandlerInterceptor;

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

// 登录拦截器
public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 登录之后用户会有session
        if (request.getSession().getAttribute("msg") == null) {
            System.out.println("=============");
            request.setAttribute("loginMsg","请先登录");
            request.getRequestDispatcher("/index").forward(request,response);
            return false;
        } else {
            return true;
        }
    }
}

当然了,我们还需要把该方法托管到SpringBoot中,写一个配置类,所谓配置类,在SpringBoot2.x后,可以直接@Configuration注解,实现WebMvcConfigurer接口,并重写addInterceptors方法

package com.hzy.config;

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 MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 拦截所有的资源,除了主页、登录请求、注册请求、注册完成和静态资源
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/","/index","/login","/toRegister","/register","/css/**","/img/**","/js/**");
    }
}
发布了423 篇原创文章 · 获赞 273 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/HeZhiYing_/article/details/104404808
今日推荐