(021)Spring Boot之拦截器HandlerInterceptor

   拦截器的使用步骤:

  第一步,实现HandlerInterceptor接口,该接口有三个方法preHandle 、postHandle 、afterCompletion

  (1)preHandle在controller执行之前调用

  (2)postHandle在controller执行之后,页面渲染之前调用

  (3)afterCompletion在页面渲染之后调用,一般用于资源清理操作

  第二步,继承WebMvcConfigurationSupport或者实现WebMvcConfigurer,重写他们的addInterceptors方法。把上一步的拦截器加进去。

  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>com.edu.spring</groupId>
    <artifactId>springboot_web</artifactId>
    <version>1.0.0</version>

    <name>springboot_web</name>
    <!-- FIXME change it to the project‘s website -->
    <url>http://www.example.com</url>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

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

</project>

  LogHandlerInterceptor.java

package com.edu.spring.springboot;

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LogHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        System.out.println("====================preHandle================="+handler.getClass().getName());
        return true;
    }

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

        System.out.println("==================postHandle==================="+handler.getClass().getName());

    }

    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("==================afterCompletion==================="+handler.getClass().getName());

    }

}

  MyWebMvcConfigurationSupport.java

package com.edu.spring.springboot;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class MyWebMvcConfigurationSupport extends WebMvcConfigurationSupport{

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        // TODO Auto-generated method stub
        registry.addInterceptor(new LogHandlerInterceptor());
    }
}

  或者MyWebMvcConfigurer.java

package com.edu.spring.springboot;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer  {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // TODO Auto-generated method stub
        registry.addInterceptor(new LogHandlerInterceptor());
    }
}

  UserController.java

package com.edu.spring.springboot;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @RequestMapping("/user/home")
    public String home(){
        System.out.println("============home=============");
        return "user home";
    }
}

  App.java

package com.edu.spring.springboot;

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

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

  浏览器输入:http://127.0.0.1:8080/user/home ,运行结果如下:

原文地址:https://www.cnblogs.com/javasl/p/11966654.html

时间: 2024-11-08 16:42:17

(021)Spring Boot之拦截器HandlerInterceptor的相关文章

Spring Boot整合拦截器

过滤器和监听器都属于Servlet 的api,还可以使用 Spring 提供的拦截器(HandlerInterceptor)进行改更精细的控制. 原文地址:https://www.cnblogs.com/natian-ws/p/10823072.html

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

1.首先编写拦截器代码 package com.sarnath.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Service; import org.springframework.web.servlet.HandlerInterceptor; import

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

作者:liuxiaopeng 链接:http://www.cnblogs.com/paddix 作者:蓝精灵lx原文:https://blog.csdn.net/liuxiao723846/article/details/80656492 参考以上两位作者文章链接进行实验整合,仅供学习交流 一.拦截器与过滤器 先理解一下AOP的概念,AOP不是一种具体的技术,而是一种编程思想. 在面向对象编程的过程中,我们很容易通过继承.多态来解决纵向扩展. 但是对于横向的功能,比如,在所有的service方法

spring boot 配置拦截器验证使用 token 登录

1.自定义登录注解 package io.xiongdi.annotation; import java.lang.annotation.*; /** * @author wujiaxing * @date 2019-07-12 * 登录校验 */ @Target(ElementType.METHOD) @Documented @Retention(RetentionPolicy.RUNTIME) public @interface Login { } 2.创建 token 实体类 packag

spring boot 添加拦截器

构建一个spring boot项目. 添加拦截器需要添加一个configuration @Configuration @ComponentScan(basePackageClasses = Application.class, useDefaultFilters = true) public class ServletContextConfig extends WebMvcConfigurationSupport { 为了方便扫描位置,我们可以写一个接口或者入口类Application放置于最外

Spring boot 自定义拦截器

1.新建一个类实现HandlerInterceptor接口,重写接口的方法 1 package com.zpark.interceptor; 2 3 import com.zpark.tools.Constants; 4 import com.zpark..tools.utils.EmptyUtils; 5 import org.slf4j.Logger; 6 import org.slf4j.LoggerFactory; 7 import org.slf4j.MDC; 8 import org

玩转spring MVC(七)----拦截器

继续在前边的基础上来学习spring MVC中拦截器的使用,下面通过一个例子来实现(完整项目在这里下载:http://download.csdn.net/detail/u012116457/8433425). 首先在项目中添加interceptor-servlet.xml来配置拦截器,当然,必须在web.xml中配置在tomcat启动时加载,如下: <!--1.配置spring分发器(是总的控制中心 被拦截的url会汇聚到该servlet) --> <servlet> <se

spring mvc +cookie+拦截器功能 实现系统自动登陆

先看看我遇到的问题: @ResponseBody @RequestMapping("/logout") public Json logout(HttpSession session,HttpServletRequest request,HttpServletResponse response) { Json j = new Json(); if (session != null) { // session.invalidate(); session.removeAttribute(&q

[转载] Spring MVC - 处理器拦截器

5.1.处理器拦截器简介 Spring Web MVC的处理器拦截器(如无特殊说明,下文所说的拦截器即处理器拦截器)类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理.   5.1.1.常见应用场景 1.日志记录:记录请求信息的日志,以便进行信息监控.信息统计.计算PV(Page View)等. 2.权限检查:如登录检测,进入处理器检测检测是否登录,如果没有直接返回到登录页面: 3.性能监控:有时候系统在某段时间莫名其妙的慢,可以通过拦截器在进入处理器之前记录开始时间