Construct a spring boot project .

Adding interceptors requires adding a configuration

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

For the convenience of scanning location , We can write an interface or an entry class Application Put it in the outermost package , This will scan the class and the class of the subpackage .

1 resources To configure

When this class is not configured , We can do it in application.ym Modify the static file location and matching method in :

# Specify the environment profile 
spring:
profiles:
active: dev
# Modify the default static path , The default is /**, When configuring hello.config.ServletContextConfig The configuration here is invalid after operation
mvc:
static-path-pattern: /static/**

But when we inherit WebMvcConfigurationSupport And configure the scan , Above resources Configuration failure , Restore default configuration . Then we need to specify the static resource location again in this class :

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

Visit like this classpath Under the static Static resources under the package url Match for /static/xxx.js. Default match static Under the static file url by /xxx.js, Although clean , But I feel idea You don't recognize this path , It's better to change to a complete path .

2.Interceptor To configure

Configure login interception or something . You need to create an interceptor class to inherit HandlerInterceptorAdapter, And then just cover where you want to intercept . such as , I'm just blocking access methods before :

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);
}
}

Write well interceptor Then you need to start creating ServletContextConfig Add this interceptor to :

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

complete ServletContextConfig by :

/*
* 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"; /**
* It turns out that if you inherit WebMvcConfigurationSupport, It's in yml The relevant contents configured in will be invalid .
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/").addResourceLocations("/**");
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
} /**
* To configure servlet Handle
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
} @Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns(FAVICON_URL)
;
} }

3.AOP Interception method

Related test code http://www.cnblogs.com/woshimrf/p/5677337.html

Ben demo Source code :

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

spring boot More about adding interceptors

  1. spring boot Add a simple example of interceptor (springBoot 2.x edition , Add interceptor , The solution to the inaccessibility of static resources )

    spring There are two main types of interceptors in this system , One is HandlerInterceptor, One is MethodInterceptor One .HandlerInterceptor HandlerInterceptor yes s ...

  2. Spring Boot Configure interceptors and achieve cross domain access

    Interceptors are powerful , Be able to go deep into the method before and after , Often used for logging . Authority checking and performance checking, etc , Almost an integral part of the project , This article is to realize Spring Boot Custom interceptor configuration . Theoretical guidance ask :Spring Boot Yes? ...

  3. spring boot Using interceptors , annotation Realization Permission filtering

    http://www.cnblogs.com/zhangXingSheng/p/7744997.html spring boot Using interceptors Realization User login blocking http://www.cnblogs. ...

  4. 【 Chapter 40 】Spring Boot Custom interceptors

    1. First, write the interceptor code package com.sarnath.interceptor; import javax.servlet.http.HttpServletRequest; import ja ...

  5. Spring boot A brief introduction to custom interceptor and interceptor redirection configuration

    Hello everyone : This article gives a brief introduction to Spring boot Interceptor configuration , Interceptor redirection problem . development tool :jdk1.8   idea2017( Paid version , Cracking course on the Internet ) 1, use first idea Create a Sp ...

  6. Spring Boot Integrated interceptors

    Filters and monitors belong to Servlet Of api, You can also use Spring Interceptors provided (HandlerInterceptor) To carry out more precise control .

  7. spring boot The interceptor is easy to use

    1.spring boot Interceptors default to : HandlerInterceptorAdapter AbstractHandlerMapping UserRoleAuthorizationIntercept ...

  8. Spring Boot The interceptors and filters ( Full version )

    author :liuxiaopeng link :http://www.cnblogs.com/paddix author : Smurfs lx original text :https://blog.csdn.net/liuxiao723846/artic ...

  9. Spring Boot (20) Interceptor

    Dynamic resources and static resources Interceptors can be called aop An implementation of , Specifically intercept background requests for dynamic resources , That is to intercept requests to the control layer , Mainly used to determine whether the user has permission to request the background . Interceptors don't intercept static resources , Such as spring boot Default static ...

Random recommendation

  1. ubuntu Command collection

    1. ctrl + Alt + F1:   Go to the pure command line . 2. ctr + Alt + T :     Open the terminal from the GUI .

  2. I wrote a H5 Version of Tetris

    After finishing the project in the internship company , It's boring . Just use H5 I wrote a few games to play . Start simple , Just a classic game of Tetris . The first effect : The number above is the score , The game doesn't consider compatibility , Only in chrome Tested on , But most modern ...

  3. java Long Of iniValue error

    Long l1 = 2500000000L; l1.intValue() The value of is negative here System.out.println(Integer.MAX_VALUE); // 2147483647 Maximum ...

  4. Windows2008 Patching( patch up )

    We all know Windows All servers need to be patched , Otherwise, the loophole is called more .Windows There are only two ways to patch a series of servers : 1. adopt Internet patch up : Go to control Panel-& ...

  5. soliworks 3D cabinet layout ( One ) Create device model library

    Take the electrical system of a helicopter as an example : One of the preconditions of 3D harness design is to create a model library for each device in the circuit ( As shown in the figure below : The arrow in the window points to 3D Parts must be added for each device ) The device has to add 3d Model , stay solidworks Progressive machine ...

  6. Java Thread learning notes ( One )

    One . Thread being created : It's an old topic . Inherit  java.lang.Thread Parent class or implementation Runnalbe Interface . Let's just say : class Thread implements Runnable Thr ...

  7. JAVA_ Read XML file

    In the project , In many cases, you need to write some configuration in xml Documents or properties In the document , Easy to modify configuration in the future , Good maintenance and so on . 1. newly build xml file <?xml version="1.0" ...

  8. C++ or C# Call external exe Analysis of

    Suppose there's an external program called A.exe, Place in directory E:\temp\ Next , And then we use C++ perhaps C# Write a program to call this A.exe Words ( Let's assume that the caller's path is in D:\invoke), The following code is usually used : // C# ...

  9. List The object to re read the God of broken Dao

    Preface List It's a common case that a set operation removes duplicate data , There are also many great gods in the blog park , Here is mainly for reference, and then I sort it out , It's mainly for your convenience , In the future, we will encounter this problem again , Just open your own link and pick up the keyboard ...

  10. Use the script to excel,csv And so on

    Article transferred from  http://blog.csdn.net/lky5387/article/details/6043009 1.-- guide excel file  select   Order number  from OpenRowSet( ...