Springboot拦截器实现

本文介绍了Springboot 2.0及更高版本中如何实现拦截器,由于WebMvcConfigurerAdapter已被废弃,现在应使用WebMvcConfigurer接口进行配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Springboot拦截器实现

下面展示一些 内联代码片

如写个登录类拦截器,继承HandlerInterceptorAdapter
若user=null即无用户,response.sendRedirect("/admin")重定向到登录页面
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        if(request.getSession().getAttribute("user") == null) {
            response.sendRedirect("/admin");
        }
        return super.preHandle(request, response, handler);
    }
}
添加配置类实现WebMvcConfigurer接口
重写addInterceptors(InterceptorRegistry)方法
addPathPatterns("/admin/**"):拦截所有 /admin/**  请求
excludePathPatterns("/admin"):排除 /admin 请求
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 WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin")
                .excludePathPatterns("/admin/login");
    }
}

值得一提的是WebMvcConfigurerAdapter类已经过时,在新版本2.x中被废弃,原因是springboot2.0以后,引用的是spring5.0,而spring5.0取消了WebMvcConfigurerAdapter,所以一开始用WebMvcConfigurerAdapter类的时候划横线不给使用才换成了WebMvcConfigurer接口

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值