devstory

Le Tutoriel de Spring Boot Interceptor

  1. Qu'est ce que Spring Interceptor?
  2. Créer le projet Spring Boot
  3. Interceptor classes
  4. Configurer  Interceptor
  5. Controllers & Views
  6. Exécution des applications

1. Qu'est ce que Spring Interceptor?

Lorsque vous arrivez à une entreprise et que vous souhaitez rencontrer le directeur de l'entreprise. Vous devez traverser les intercepteurs (interceptors) qui peuvent être un portier, un réceptionniste, ...

Dans Spring, lorsqu'une demande est envoyée au Controller de ressort, elle devra traverser Interceptor(0 ou plus) avant d'être traitée par Controller.
Spring Interceptor est un concept qui est assez similaire à Servlet Filter.

Spring Interceptor est seulement appliqué aux commandes qui sont envoyées à un Controller.
Vous pouvez utiliser Interceptor pour effectuer quelques tâches, telles que l'éciture Log, l'ajout ou la mise à jour la configuration avant la commande soit traitée par Controller, ...
Une des applications Spring Boot MVC utilisant Interceptor comme "Application web multilingue". Vous pouvez voir plus l'application ici:
Votre classe Interceptor doit mettre en oeuvre l'interface org.springframework.web.servlet.HandlerInterceptor ou extendre de la classe org.springframework.web.servlet.handler.HandlerInterceptorAdapter.
Vous devez mettre en oeuvre 3 méthodes abstraires:
public boolean preHandle(HttpServletRequest request,
                         HttpServletResponse response,
                         Object handler)


public void postHandle(HttpServletRequest request,
                       HttpServletResponse response,
                       Object handler,
                       ModelAndView modelAndView)


public void afterCompletion(HttpServletRequest request,
                            HttpServletResponse response,
                            Object handler,
                            Exception ex)
Remarque: La méthode preHandle renvoie true ou false. Si elle renvoie true cela signifie que la demande continuera à atteindre sa destination (est un Controller) .
Chaque demande peut passer par beaucoup d'Interceptor. La figure ci-dessous illustre cela.

2. Créer le projet Spring Boot

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.o7planning</groupId>
    <artifactId>SpringBootInterceptor</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>SpringBootInterceptor</name>
    <description>Spring Boot + Interceptor</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>
SpringBootInterceptorApplication.java
package org.o7planning.sbinterceptor;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootInterceptorApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootInterceptorApplication.class, args);
    }
    
}

3. Interceptor classes

LogInterceptor est appliqué à toutes les demandes venant à un Controller. (Voir la configuration dans WebMvcConfig).
LogInterceptor.java
package org.o7planning.sbinterceptor.interceptor;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LogInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		long startTime = System.currentTimeMillis();
		System.out.println("\n-------- LogInterception.preHandle --- ");
		System.out.println("Request URL: " + request.getRequestURL());
		System.out.println("Start Time: " + System.currentTimeMillis());

		request.setAttribute("startTime", startTime);

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, //
			Object handler, ModelAndView modelAndView) throws Exception {

		System.out.println("\n-------- LogInterception.postHandle --- ");
		System.out.println("Request URL: " + request.getRequestURL());

		// You can add attributes in the modelAndView
		// and use that in the view page
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, //
			Object handler, Exception ex) throws Exception {
		System.out.println("\n-------- LogInterception.afterCompletion --- ");

		long startTime = (Long) request.getAttribute("startTime");
		long endTime = System.currentTimeMillis();
		System.out.println("Request URL: " + request.getRequestURL());
		System.out.println("End Time: " + endTime);

		System.out.println("Time Taken: " + (endTime - startTime));
	}

}
OldLoginInterceptor est un intercepteur (interceptor), si un utilisateur saisit le lien /admin/oldLogin,Il redirige vers le nouveau lien /admin/login.
OldLoginInterceptor.java
package org.o7planning.sbinterceptor.interceptor;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class OldLoginInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		System.out.println("\n-------- OldLoginInterceptor.preHandle --- ");
		System.out.println("Request URL: " + request.getRequestURL());
		System.out.println("Sorry! This URL is no longer used, Redirect to /admin/login");

		response.sendRedirect(request.getContextPath() + "/admin/login");
		return false;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, //
			Object handler, ModelAndView modelAndView) throws Exception {

		// This code will never be run.
		System.out.println("\n-------- OldLoginInterceptor.postHandle --- ");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, //
			Object handler, Exception ex) throws Exception {
		
		// This code will never be run.
		System.out.println("\n-------- QueryStringInterceptor.afterCompletion --- ");
	}

}
AdminInterceptor.java
package org.o7planning.sbinterceptor.interceptor;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class AdminInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        System.out.println("\n-------- AdminInterceptor.preHandle --- ");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, //
            Object handler, ModelAndView modelAndView) throws Exception {
        
        System.out.println("\n-------- AdminInterceptor.postHandle --- ");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, //
            Object handler, Exception ex) throws Exception {

        System.out.println("\n-------- AdminInterceptor.afterCompletion --- ");
    }

}

4. Configurer  Interceptor

WebMvcConfig.java
package org.o7planning.sbinterceptor.config;

import org.o7planning.sbinterceptor.interceptor.AdminInterceptor;
import org.o7planning.sbinterceptor.interceptor.LogInterceptor;
import org.o7planning.sbinterceptor.interceptor.OldLoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

   //
   @Override
   public void addInterceptors(InterceptorRegistry registry) {
      // LogInterceptor apply to all URLs.
      registry.addInterceptor(new LogInterceptor());

      // Old Login url, no longer use.
      // Use OldURLInterceptor to redirect to a new URL.
      registry.addInterceptor(new OldLoginInterceptor())//
            .addPathPatterns("/admin/oldLogin");

      // This interceptor apply to URL like /admin/*
      // Exclude /admin/oldLogin
      registry.addInterceptor(new AdminInterceptor())//
            .addPathPatterns("/admin/*")//
            .excludePathPatterns("/admin/oldLogin");
   }

}

5. Controllers & Views

MainController.java
package org.o7planning.sbinterceptor.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MainController {

	@RequestMapping(value = { "/", "/test" })
	public String test(Model model) {

		System.out.println("\n-------- MainController.test --- ");

		System.out.println(" ** You are in Controller ** ");

		return "test";
	}

	// This path is no longer used.
	// It will be redirected by OldLoginInterceptor
	@Deprecated
	@RequestMapping(value = { "/admin/oldLogin" })
	public String oldLogin(Model model) {

		// Code here never run.
		return "oldLogin";
	}

	@RequestMapping(value = { "/admin/login" })
	public String login(Model model) {

		System.out.println("\n-------- MainController.login --- ");

		System.out.println(" ** You are in Controller ** ");

		return "login";
	}

}
test.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">

   <head>
      <meta charset="UTF-8" />
      <title>Spring Boot Mvc Interceptor example</title>
   </head>

   <body>
      <div style="border: 1px solid #ccc;padding: 5px;margin-bottom:10px;">
         <a th:href="@{/}">Home</a>
         &nbsp;&nbsp; | &nbsp;&nbsp;
         <a th:href="@{/admin/oldLogin}">/admin/oldLogin (OLD URL)</a>  
      </div>

      <h3>Spring Boot Mvc Interceptor</h3>
      
      <span style="color:blue;">Testing LogInterceptor</span>
      <br/><br/>

      See Log in Console..

   </body>
</html>
login.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
   <head>
      <meta charset="UTF-8" />
      <title>Spring Boot Mvc Interceptor example</title>
   </head>
   <body>
   
      <div style="border: 1px solid #ccc;padding: 5px;margin-bottom:10px;">
         <a th:href="@{/}">Home</a>
         &nbsp;&nbsp; | &nbsp;&nbsp;
         <a th:href="@{/admin/oldLogin}">/admin/oldLogin (OLD URL)</a>  
      </div>
      
      <h3>This is Login Page</h3>
      
      <span style="color:blue">Testing OldLoginInterceptor &amp; AdminInterceptor</span>
      <br/><br/>
      See more info in the Console.
      
   </body>
   
</html>

6. Exécution des applications

Testez le cas lorsqu'un utilisateur visite une page, LogInterceptor enregistre les informations pertinentes (adresse de la page, temps d'accès) et calcule le temps pendant lequel le Web Server a répondu à la demande/ requête.
-------- LogInterception.preHandle ---
Request URL: http://localhost:8080/
Start Time: 1512231713663

-------- MainController.test ---
 ** You are in Controller **

-------- LogInterception.postHandle ---
Request URL: http://localhost:8080/

-------- LogInterception.afterCompletion ---
Request URL: http://localhost:8080/
End Time: 1512231713665
Time Taken: 2
Testez le cas lorsqu'un utilisateur visite une ancienne page de connexion (n'est plus utilisée), le OldLoginInterceptor redirige la demande vers la nouvelle page de connexion.
-------- LogInterception.preHandle ---
Request URL: http://localhost:8080/admin/oldLogin
Start Time: 1512231812219

-------- OldLoginInterceptor.preHandle ---
Request URL: http://localhost:8080/admin/oldLogin
Sorry! This URL is no longer used, Redirect to /admin/login

-------- LogInterception.afterCompletion ---
Request URL: http://localhost:8080/admin/oldLogin
End Time: 1512231812219
Time Taken: 1

-------- LogInterception.preHandle ---
Request URL: http://localhost:8080/admin/login
Start Time: 1512231812222

-------- AdminInterceptor.preHandle ---

-------- MainController.login ---
 ** You are in Controller **

-------- AdminInterceptor.postHandle ---

-------- LogInterception.postHandle ---
Request URL: http://localhost:8080/admin/login

-------- AdminInterceptor.afterCompletion ---

-------- LogInterception.afterCompletion ---
Request URL: http://localhost:8080/admin/login
End Time: 1512231812227
Time Taken: 5

Tutoriels Spring Boot

Show More