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
spring boot 添加拦截器的更多相关文章
- spring boot 添加拦截器的简单实例(springBoot 2.x版本,添加拦截器,静态资源不可访问解决方法)
spring中拦截器主要分两种,一个是HandlerInterceptor,一个是MethodInterceptor 一.HandlerInterceptor HandlerInterceptor是s ...
- Spring Boot配置拦截器及实现跨域访问
拦截器功能强大,能够深入方法前后,常应用于日志记录.权限检查和性能检测等,几乎是项目中不可或缺的一部分,本文就来实现Spring Boot自定义拦截器的配置. 理论指导 问:Spring Boot怎么 ...
- spring boot 使用拦截器,注解 实现 权限过滤
http://www.cnblogs.com/zhangXingSheng/p/7744997.html spring boot 使用拦截器 实现 用户登录拦截 http://www.cnblogs. ...
- 【第四十章】Spring Boot 自定义拦截器
1.首先编写拦截器代码 package com.sarnath.interceptor; import javax.servlet.http.HttpServletRequest; import ja ...
- Spring boot自定义拦截器和拦截器重定向配置简单介绍
大家好: 本文简单介绍一下用于权限控制的Spring boot拦截器配置,拦截器重定向问题. 开发工具:jdk1.8 idea2017(付费版,网上找的破解教程) 1,首先使用idea创建一个Sp ...
- Spring Boot整合拦截器
过滤器和监听器都属于Servlet 的api,还可以使用 Spring 提供的拦截器(HandlerInterceptor)进行改更精细的控制.
- spring boot的拦截器简单使用
1.spring boot拦截器默认有: HandlerInterceptorAdapter AbstractHandlerMapping UserRoleAuthorizationIntercept ...
- Spring Boot之拦截器与过滤器(完整版)
作者:liuxiaopeng 链接:http://www.cnblogs.com/paddix 作者:蓝精灵lx原文:https://blog.csdn.net/liuxiao723846/artic ...
- Spring Boot (20) 拦截器
动态资源和静态资源 拦截器可以算是aop的一种实现,专门拦截对动态资源的后台请求,也就是拦截对控制层的请求,主要用于判断用户是否有权限请求后台.拦截器不会拦截静态资源,如spring boot默认静态 ...
随机推荐
- 学习笔记:delphi多线程知识
最近一直在温习旧的知识,刚好学习了一下Java的线程安全方面的知识,今天想起之前一直做的Delphi开发,所以还是有必要温习一下,看看这些不同的编程语言有什么不同之处. Delphi的线程同步方法: ...
- Change the Target Recovery Time of a Database (SQL Server) 间接-checkpoints flushcache flushcache-message
Change the Target Recovery Time of a Database (SQL Server) 间接checkpoints flushcache flushcache-mes ...
- CYQ.Data V5 MDataTable 专属篇介绍
前言 以前一两个月才出一篇,这三天有点变态地连续1天1篇(其实都是上周末两天写好的存货). 短期应该没有新的和此框架相关的文章要写了,这应该是最后一篇,大伙且看且珍惜. 前两篇讲数据库读写分离和分布式 ...
- 解读ASP.NET 5 & MVC6系列(5):Configuration配置信息管理
在前面的章节中,我们知道新版的MVC程序抛弃了原来的web.config文件机制,取而代替的是config.json,今天我们就来深入研究一下配置文件的相关内容. 基本用法 新版的配置信息机制在Mic ...
- ABP理论学习之启动配置
返回总目录 本篇目录 配置ABP 配置模块 为模块创建配置 为了在应用启动时配置ABP和模块,ABP提供了一个基础设施. 配置ABP 配置ABP是在模块的PreInitialize事件中完成的.下面的 ...
- MySQL KEY分区
200 ? "200px" : this.width)!important;} --> 介绍 KEY分区和HASH分区相似,但是KEY分区支持除text和BLOB之外的所有数 ...
- Distributed MVCC based cross-row transaction
The algorithm for supporting distributed MVCC based cross-row transactions on top of a distributed k ...
- [ASP.NET MVC 大牛之路]02 - C#高级知识点概要(1) - 委托和事件
在ASP.NET MVC 小牛之路系列中,前面用了一篇文章提了一下C#的一些知识点.照此,ASP.NET MVC 大牛之路系列也先给大家普及一下C#.NET中的高级知识点.每个知识点不太会过于详细,但 ...
- maven profile的使用
作为一名程序员,在开发的过程中,经常需要面对不同的运行环境(开发环境.测试环境.生产环境.内网环境.外网环境等等),在不同的环境中,相关的配置一般不一样,比如数据源配置.日志文件配置.以及一些软件运行 ...
- css+div常用属性备忘录
学习软件设计有一年多了,明年五月就要毕业了.回头看看发现自己其实挺差劲的. 最近开通了博客所以就整理了一下笔记,在这里发布一下自己以前学习css时总是记不住去翻书又很常用的属性,都是一些很基础的. 大 ...