spring boot 添加拦截器

构建一个spring boot项目。

添加拦截器需要添加一个configuration

@Configuration
@ComponentScan(basePackageClasses = Application.class, useDefaultFilters = true)
public class ServletContextConfig extends WebMvcConfigurationSupport {

为了方便扫描位置,我们可以写一个接口或者入口类Application放置于最外一层的包内,这样就会扫描该类以及子包的类。

1 resources配置

在没有配置这个类的时候,我们可以在application.ym中修改静态文件位置和匹配方式:

#指定环境配置文件
spring:
  profiles:
    active: dev
  # 修改默认静态路径,默认为/**,当配置hello.config.ServletContextConfig后此处配置失效
  mvc:
    static-path-pattern: /static/**

但当我们继承了WebMvcConfigurationSupport 并配置扫描后,上述resources的配置失效,还原默认配置。那么我们需要在这个类中再次指定静态资源位置:

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/").addResourceLocations("/**");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

这样访问classpath下的static包下的静态资源的url匹配为/static/xxx.js。默认匹配static下的静态文件url为/xxx.js,虽然清洁,但我感觉idea不会识别这种路径,还是改成完整的路径比较好。

2.Interceptor配置

配置登录拦截或者别的。需要创建一个拦截器类来继承HandlerInterceptorAdapter,然后只需要覆盖你想要拦截的位置就可以了。比如,我只是拦截访问方法之前:

package hello.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * Created by miaorf on 2016/8/3.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("Authorization");
        logger.info("The authorization is: {}",authorization);
        return super.preHandle(request, response, handler);
    }
}

写好interceptor之后需要在开始创建的ServletContextConfig中添加这个拦截器:

@Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(FAVICON_URL)
        ;
    }

完整的ServletContextConfig为:

/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014-2016 abel533@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package hello.config;

import hello.Application;
import hello.interceptor.LoginInterceptor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 *
 */
@Configuration
@ComponentScan(basePackageClasses = Application.class, useDefaultFilters = true)
public class ServletContextConfig extends WebMvcConfigurationSupport {

    static final private String FAVICON_URL = "/favicon.ico";
    static final private String PROPERTY_APP_ENV = "application.environment";
    static final private String PROPERTY_DEFAULT_ENV = "dev";



    /**
     * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/").addResourceLocations("/**");
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }


    /**
     * 配置servlet处理
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(FAVICON_URL)
        ;
    }

}

3.AOP拦截方法

相关测试代码http://www.cnblogs.com/woshimrf/p/5677337.html

本demo源码:

https://github.com/Ryan-Miao/spring-boot-demo

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏蓝天

基于zookeeper的主备切换方法

继承CZookeeperHelper即可快速实现主备切换: https://github.com/eyjian/mooon/blob/master/mooo...

1212
来自专栏女程序员的日常

STM8S——Analog/digital converter (ADC)

1、ADC1 and ADC2 are 10-bit successive approximation Anolog to Digital Converters...

3141
来自专栏大数据架构

Java进阶(五)Java I/O模型从BIO到NIO和Reactor模式

1875
来自专栏JavaEdge

Tomcat架构解析之3 Connector NIOAcceptorPollerWorkerNioSelectorPool

2804
来自专栏Aloys的开发之路

org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter与org.apache.struts2.dispatcher.

使用Eclipse启动Maven+Struts项目报错,报错日志如下: 2016-08-31 22:00:47 INFO ContextLoader:325 ...

2415
来自专栏javathings

Java 的 NIO 是如何工作的?

在这个数据爆炸的时代,有大量的数据在系统中流动,一个应用系统的瓶颈往往都是 IO 瓶颈。传统的 javaIO 模型是 BIO,也就是同步阻塞 IO,数据在写入 ...

1251
来自专栏架构师之旅

【Java SE】Java NIO系列教程(一) Java NIO 概述

Java NIO 由以下几个核心部分组成: Channels Buffers Selectors 虽然Java NIO 中除此之外还有很多类和组件,但在我看来...

2087
来自专栏Janti

Java中的NIO基础知识

上一篇介绍了五种NIO模型,本篇将介绍Java中的NIO类库,为学习netty做好铺垫

1153
来自专栏运维前线

umount: /var: device is busy

去掉挂载显示device is busy 出现此问题是当前挂载点上面有进程存在 [root@zabbix ~]# umount /dev/mapper/v...

2239
来自专栏Python

利用ForgeryPy生成虚拟数据

 在程序研发过程中,我们往往需要大量的虚拟实验数据。Python中有多个包可以用于生成虚拟数据,其中功能较为完善的是ForgeryPy。

870

扫码关注云+社区