SpringBoot 2.x 自定义拦截器并解决静态资源访问被拦截问题

说明:

在自己写一个spring boot demo的时候,想着根据session的过期时间来返回登录页面,在自定义完拦截器以后功能可以实现,但是静态资源却无法访问,通过查找文档发现spring boot 1.x和2.x是不一样,所以特别记录一下,留给后面的同学避免踩坑.

1.x和2.x的静态资源访问区别

  • 1.x的resources/static目录下的静态资源可以直接访问,并且访问路径上不用带static,当有配置自定义HandlerInterceptor拦截器时,请求静态资源路径不会被拦截。
  • 2.x的如果自定义HandlerInterceptor拦截器时访问静态资源就会被同步拦截,这样为了实现session过期而跳转登录页面功能就会受影响.

项目的目录

}O31{R6DQ}AQZLRQR0WVU`D.png

自定义拦截器

/**
 * UserSecurityInterceptor
 * Created with IntelliJ IDEA.
 * Author: yangyongkang
 * Date: 2018/8/22
 * Time: 14:20
 */
@Component
public class UserSecurityInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserModel info = (UserModel) redisCacheTemplate.opsForValue().get(request.getSession().getId());
        if (info == null || StringUtils.isEmpty(info)) {
            response.sendRedirect(request.getContextPath() + "/view/login");
            return false;
        }
        return true;
    }

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

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}
  • 因为我的session是放在redis里面的,所以只需要从redis里面取即可.

配置访问路径及静态资源

/**
 * 登陆拦截控制类
 * Created with IntelliJ IDEA.
 * Author: yangyongkang
 * Date: 2018/8/22
 * Time: 14:17
 */
@Configuration
public class WebMvcConfig implements  WebMvcConfigurer {
    @Autowired
    private UserSecurityInterceptor securityInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration addInterceptor = registry.addInterceptor(securityInterceptor);
        // 排除配置
        addInterceptor.excludePathPatterns("/error");
        addInterceptor.excludePathPatterns("/static/**");//排除静态资源
        addInterceptor.excludePathPatterns("/view/login");
        addInterceptor.excludePathPatterns("/login/check");
        // 拦截配置
        addInterceptor.addPathPatterns("/**");
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");//
    }
}
  • 这样有一个问题,不明白为啥要这样设计,因为如果一旦控制器内有static开头的访问路径的话,拦截器就不会拦截了.

页面加载方式

//第一种在thymeleaf模版内部
    <link type="text/css" th:href="@{/static/css/page/bootstrap.min.css}" rel="stylesheet">
    <link type="text/css" th:href="@{/static/css/page/font-awesome.css}" rel="stylesheet">
    <link type="text/css" th:href="@{/static/css/page/animate.css}" rel="stylesheet">
    <link type="text/css" th:href="@{/static/css/page/style.css}" rel="stylesheet">
    <link type="text/css" th:href="@{/static/css/page/login.css}" rel="stylesheet">
    
//第二种
    <link href="/static/css/page/bootstrap.min.css" rel="stylesheet">
    <link href="/static/css/page/font-awesome.css" rel="stylesheet">
    <link href="/static/css/page/animate.css" rel="stylesheet">
    <link href="/static/css/page/style.css" rel="stylesheet">

最后特别注意一下

  • 在spring boot2.x中已经无法再使用WebMvcConfigurationAdapter,官方声明已过时.
  • 可以继承WebMvcConfigurationSupport或者实现WebMvcConfigurer
implements WebMvcConfigurer : 
//不会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
@EnableWebMvc + implements WebMvcConfigurer :
// 会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
extends WebMvcConfigurationSupport :
//会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置
extends DelegatingWebMvcConfiguration :
//会覆盖@EnableAutoConfiguration关于WebMvcAutoConfiguration的配置



作者:i玄离
链接:https://www.jianshu.com/p/c638b3166963
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中设置拦截器时,需要注意一些细节。 首先,如果你的静态资源图片不显示,可能是因为拦截器配置不当导致的。在配置拦截器时,可以使用`addPathPatterns()`方法设置需要拦截的路径,同时也需要使用`excludePathPatterns()`方法排除不需要拦截的路径。如果没有正确地配置排除路径,就可能会导致静态资源无法访问。 另外,还需要在配置文件中设置静态资源路径。在Spring Boot中,默认情况下静态资源路径为`/static`、`/public`、`/resources`和`/META-INF/resources`。如果你的静态资源存储在其他路径下,需要在配置文件中进行设置。 以下是一个示例拦截器配置,可以参考一下: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new UserInterceptor()) .addPathPatterns("/user/**") .excludePathPatterns("/user/login", "/user/register"); registry.addInterceptor(new AdminInterceptor()) .addPathPatterns("/admin/**") .excludePathPatterns("/admin/login"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); } } ``` 在上面的示例中,`UserInterceptor`和`AdminInterceptor`分别是自定义拦截器类。`addPathPatterns()`方法设置需要拦截的路径,`excludePathPatterns()`方法排除不需要拦截的路径。`addResourceHandlers()`方法设置静态资源路径为`/static/**`,存储在`classpath:/static/`下。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值