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默认静态 ...
随机推荐
- 2016/11/17 周四 <javascript的封装简单示例>
这是一个简单的javascript代码封装的示例以及封装后的调用方法: var ticker={ n:0, add:function() { this.n++; }, show:function() ...
- Independent Components Analysis:独立成分分析
一.引言 ICA主要用于解决盲源分离问题.需要假设源信号之间是统计独立的.而在实际问题中,独立性假设基本是合理的. 二.随机变量独立性的概念 对于任意两个随机变量X和Y,如果从Y中得不到任何关于X的信 ...
- Coping with the TCP TIME-WAIT state on busy Linux servers
Coping with the TCP TIME-WAIT state on busy Linux servers 文章源自于:https://vincent.bernat.im/en/blog/20 ...
- LB 负载均衡的层次结构
作为后端应用的开发者,我们经常开发.调试.测试完我们的应用并发布到生产环境,用户就可以直接访问到我们的应用了.但对于互联网应用,在你的应用和用户之间还隔着一层低调的或厚或薄的负载均衡层软件,它们不显山 ...
- MVC学习二:基础语法
目录 一:重载方法的调用 二:数据的传递 三:生成控件 四:显示加载视图 五:强类型视图 六:@Response.Write() 和 @Html.Raw()区别 七:视图中字符串的输入 八:模板页 一 ...
- Linux下的.NET之旅:第一站,CentOS+Mono+Xsp构建最简单的ASP.NET服务器
一.Mono产生的背景 由于Linux/Unix等有更强的安全性.运行效率高.拥有大量优秀的开源组件,而.Net则有着其他语言无与伦比的开发效率,因此在非微软平台下运行.Net程序的需求很强烈.Mon ...
- 一个App完成入门篇-终结篇(八)- 应用收官
经过以上几步的学习,我们终于来到最后一个步骤了,应用APP也接近尾声. 通过之前的几节教程,不知道您对使用DeviceOne开发一个应用是不是已经得心应手了,本节教程将教会大家如何在开发完成之后通过D ...
- ystep jQuery流程、步骤插件
今天小菜给大家带来又一款给力jQuery插件:ystep. 从名称上大致可以看出,这是一个流程步骤插件. 如果无意外的话,这可能是小菜近期最后一个作品了...苦逼的小菜即将创业,可能就没时间折腾啦~好 ...
- [ASP.NET MVC 小牛之路]11 - Filter
Filter(筛选器)是基于AOP(面向方面编程)的设计,它的作用是对MVC框架处理客户端请求注入额外的逻辑,以非常简单优美的方式实现横切关注点(Cross-cutting Concerns).横切关 ...
- Servlet程序中玩验证码
验证码思想:所谓验证码就是产生若干随机数,存放到session中,然后在servlet中获取session中的该值与页面输入值相比较,进而判断正误. 产生验证码的方法: 随机数放在图片中,封装为一 ...