栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot之WebMvcConfigurer拦截器的常用使用详解

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot之WebMvcConfigurer拦截器的常用使用详解

目录
  • 1.引入pom依赖
  • 2. 启动类配置
  • 3.resources包下数据
  • 4.HandlerInterceptor 自定义拦截器实例配置
  • 5.WebMvcConfigurer 自定义拦截器配置
    • `5.1 启用并注册自定义拦截器实例`
      • 5.11 拦截器测试
    • `5.2 自定义资源映射`
      • 5.21 自定义资源映射测试
    • 5.3 通过路径自动跳转到一个页面
      • 5.31通过路径自动跳转到一个页面测试
    • `5.4 addCorsMappings(CorsRegistry registry) 设置跨域`
    • 5.5 addFormatters(FormatterRegistry registry)数据格式化器配置
      • 5.51 首先实现格式化配置实例(这里用日期做实例)
      • 5.52 数据格式化器配置测试
  • 链接:[SpringBoot之WebMvcConfigurer拦截器的常用使用详解 源代码下载地址](https://download.csdn.net/download/JAVA_MHH/34036195)

1.引入pom依赖
  • 因为用到拦截器的 几乎都是web项目,引入下web包 拦截器对象也在web包里
  • thymeleaf: 查看静态界面;
    
    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.2.RELEASE
    

    
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

    


2. 启动类配置
  • 只需要注意下 其它的类都要在启动类同包或及下层目录即可 让@SpringBootApplication中@ComponentScan扫描到;
  • 如果类不在同级目录或下层目录 可以用@import(Xxx.class)引入;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


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


3.resources包下数据
  • 主要测试拦截器相应的几个功能,它们的内容并不重要;

4.HandlerInterceptor 自定义拦截器实例配置
  • 三个方法的运行顺序为: preHandle -> postHandle -> afterCompletion;
  • 如果preHandle返回值为false,三个方法仅运行preHandle;
  • 如果运行拦截放行后的代码出错,则不会执行postHandle;
  • 自定义拦截器实例需要实现HandleInterceptor接口;
  • 注入到 ioc 自定义拦截器配置需要使用到 拦截器实例;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//自定义拦截器
//自定义拦截器需要实现HandleInterceptor接口
@Component
public class MyInterceptor implements HandlerInterceptor {
    //处理器运行之前执行
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("前置运行----a1");
        //返回值为false将拦截原始处理器的运行
        //如果配置多拦截器,返回值为false将终止当前拦截器后面配置的拦截器的运行
        System.out.println(handler);
        return true;
    }

    //处理器运行之后执行
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("后置运行----b1");
        System.out.println(handler);
        System.out.println(modelAndView);
    }

    //所有拦截器的后置执行全部结束后,执行该操作
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {
        System.out.println("完成运行----c1");
        System.out.println(handler);
        System.out.println(ex);
    }

    //三个方法的运行顺序为    preHandle -> postHandle -> afterCompletion
    //如果preHandle返回值为false,三个方法仅运行preHandle
}


5.WebMvcConfigurer 自定义拦截器配置
  • WebMvcConfigurer是一个接口,提供例如跨域设置、自定义的拦截器、类型转化器等等
  • 跨域这方面,我并不打算用拦截器来做 用网关的过滤器会更好,这里就开阔下思路 拦截器 也能做跨域设置
5.1 启用并注册自定义拦截器实例
  • 将拦截器实例 从ioc获取出来 将拦截器当作入参传入InterceptorRegistry();
  • 一定要指定拦截器路径和排除拦截路径;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

//自定义拦截器
@Configuration
public class WebConfigurer implements WebMvcConfigurer {


    @Autowired //把你写的自定义拦截器实例注入进来
    private MyInterceptor myInterceptor;

    // 这个方法用来注册拦截器,我们自己写好的拦截器需要通过这里添加注册才能生效
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //创建InterceptorRegistration对象并将自定义拦截器传入;
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(myInterceptor);
        //addPathPatterns方法(指定拦截路径,往往使用 "

//        interceptorRegistration.pathMatcher(new PathMatcher() {
//            @Override
//            public boolean isPattern(String s) {
//                return false;
//            }
//
//            @Override
//            public boolean match(String s, String s1) {
//                return false;
//            }
//
//            @Override
//            public boolean matchStart(String s, String s1) {
//                return false;
//            }
//
//            @Override
//            public String extractPathWithinPattern(String s, String s1) {
//                return null;
//            }
//
//            @Override
//            public Map extractUriTemplateVariables(String s, String s1) {
//                return null;
//            }
//
//            @Override
//            public Comparator getPatternComparator(String s) {
//                return null;
//            }
//
//            @Override
//            public String combine(String s, String s1) {
//                return null;
//            }
//        });
//        registry.addInterceptor(myInterceptor).addPathPatterns(") {
//		this.datePattern=datePattern;
		this.dateFormat = new SimpleDateFormat(datePattern);
	}
 
	// 显示Formatter的T类型对象
	public String print(Date date,Locale locale){
		return dateFormat.format(date);
	}
	
	// 解析文本字符串返回一个Formatter的T类型对象。
	public Date parse(String source, Locale locale) throws ParseException {
		try {
			return dateFormat.parse(source);
		} catch (Exception e) {
			throw new IllegalArgumentException();
		}
		
	}
}

5.52 数据格式化器配置测试
  • 前端传参入口
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

@RestController
@RequestMapping("/mhh/interceptor")
public class InterceptorTestController {

    @GetMapping("getDate")
    public Date getDate(@RequestParam("date") Date date) {
        return date;
    }
}
  • 这里注意传参的格式要和日期类型模板对应起来









链接:SpringBoot之WebMvcConfigurer拦截器的常用使用详解 源代码下载地址
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/344981.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号