构建一个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

spring boot 添加拦截器的更多相关文章

  1. spring boot 添加拦截器的简单实例(springBoot 2.x版本,添加拦截器,静态资源不可访问解决方法)

    spring中拦截器主要分两种,一个是HandlerInterceptor,一个是MethodInterceptor 一.HandlerInterceptor HandlerInterceptor是s ...

  2. Spring Boot配置拦截器及实现跨域访问

    拦截器功能强大,能够深入方法前后,常应用于日志记录.权限检查和性能检测等,几乎是项目中不可或缺的一部分,本文就来实现Spring Boot自定义拦截器的配置. 理论指导 问:Spring Boot怎么 ...

  3. spring boot 使用拦截器,注解 实现 权限过滤

    http://www.cnblogs.com/zhangXingSheng/p/7744997.html spring boot 使用拦截器 实现 用户登录拦截 http://www.cnblogs. ...

  4. 【第四十章】Spring Boot 自定义拦截器

    1.首先编写拦截器代码 package com.sarnath.interceptor; import javax.servlet.http.HttpServletRequest; import ja ...

  5. Spring boot自定义拦截器和拦截器重定向配置简单介绍

    大家好: 本文简单介绍一下用于权限控制的Spring boot拦截器配置,拦截器重定向问题. 开发工具:jdk1.8   idea2017(付费版,网上找的破解教程) 1,首先使用idea创建一个Sp ...

  6. Spring Boot整合拦截器

    过滤器和监听器都属于Servlet 的api,还可以使用 Spring 提供的拦截器(HandlerInterceptor)进行改更精细的控制.

  7. spring boot的拦截器简单使用

    1.spring boot拦截器默认有: HandlerInterceptorAdapter AbstractHandlerMapping UserRoleAuthorizationIntercept ...

  8. Spring Boot之拦截器与过滤器(完整版)

    作者:liuxiaopeng 链接:http://www.cnblogs.com/paddix 作者:蓝精灵lx原文:https://blog.csdn.net/liuxiao723846/artic ...

  9. Spring Boot (20) 拦截器

    动态资源和静态资源 拦截器可以算是aop的一种实现,专门拦截对动态资源的后台请求,也就是拦截对控制层的请求,主要用于判断用户是否有权限请求后台.拦截器不会拦截静态资源,如spring boot默认静态 ...

随机推荐

  1. wamp环境 安装memcache 扩展

    这两天在研究tp的memcached缓存 总是遇到坑 在网上找了很多教程看终于弄出来了现在拿出来分享 首先安装memcached下载memcache压缩包 使用cmd以管理员命令去安装 E:\wamp ...

  2. 初试Office 365企业版E3

    Microsoft Office 365 团队给了所有现任的MVP 12个月的微软 Office 365 企业 E3 订阅,今天激活账号并试用了一下,发现非常强大,本文简要介绍下Office 365 ...

  3. (DNS被劫持所导致的)QQ音乐与视频网页打开很慢的解决方法

    这周开始发现一个很让人抓狂的现象,QQ音乐网页(http://y.qq.com)与QQ视频(http://v.qq.com/)网页打开超慢,甚至是无法打开,严重影响了业余的音乐视频生活. 以QQ视频为 ...

  4. .NET单元测试的艺术-1.入门

    开篇:最近在看Roy Osherove的<单元测试的艺术>一书,颇有收获.因此,将其记录下来,并分为四个部分分享成文,与各位Share.本篇作为入门,介绍了单元测试的基础知识,例如:如何使 ...

  5. android内部培训视频_第三节 常用控件(Button,TextView,EditText,AutocompleteTextView)

    第三节:常用控件 一.Button 需要掌握的属性: 1.可切换的背景 2.9.png使用 3.按钮点击事件 1)  onClick 3) 匿名类 4) 公共类 二.TextView 常用属性 1.a ...

  6. 有一个团队协同工具,叫Worktile

    项目管理,本是一个老生常谈的话题,曾几何时大碗云集在这个市场,其中不乏出现像微软.SAP.IBM.用友这样的名字.复杂而又冗繁的流程控制,让人们划分成两类人,一类是会使用这些工具和系统的人,另一类是不 ...

  7. EF:Oracle.DataAccess.Client.OracleException: ORA-12154: TNS:could not resolve the connect identifier specified

    报告错误:Oracle.DataAccess.Client.OracleException: ORA-12154: TNS:could not resolve the connect identifi ...

  8. Worktile 技术架构概要

    其实早就该写这篇博客了,一直说忙于工作没有时间,其实时间挤挤总会有的,可能就是因为懒吧!从2013年11月一直拖到现在,今天就简单谈谈 Worktile 的技术架构吧 . Worktile 自上线到现 ...

  9. PHP的pcntl多进程

    PHP使用PCNTL系列的函数也能做到多进程处理一个事务.比如我需要从数据库中获取80w条的数据,再做一系列后续的处理,这个时候,用单进程?你可以等到明年今天了...所以应该使用pcntl函数了. 假 ...

  10. 《Node即学即用》—— 读后总结

    导图